gpt4 book ai didi

c++ - 为什么覆盖全局新运算符和类特定运算符不是模棱两可的行为?

转载 作者:可可西里 更新时间:2023-11-01 15:48:22 24 4
gpt4 key购买 nike

考虑以下代码:

class Foo 
{
public:
//class-specific
Foo operator+(Foo& rhs)
{
return Foo(); //Just return a temporary
}

void* operator new(size_t sd)
{
return malloc(sd);
}
};

//global
Foo operator+(Foo& lhs, Foo& rhs)
{
return Foo();
}

void* operator new(size_t sd)
{
return malloc(sd);
}

此代码无法编译,声明调用不明确,因为它匹配两个运算符:

Foo a, b;
a + b;

但是这个带有 new 运算符的编译得很好,并且会调用特定于类的那个。

Foo* a = new Foo();

为什么它不会导致编译错误?编译器是否以不同方式对待 new 运算符? (对标准的任何引用将不胜感激。)

最佳答案

Why doesn't it result in a compile error? Does the compiler treat the new operator differently? (Any citation to the standard would be appreciated)

关于全局 new 和类特定 new 之间的优先级,引用文献说 this :

As described in allocation function, the C++ program may provide global and class-specific replacements for these functions. If the new-expression begins with the optional :: operator, as in ::new T or ::new T[n], class-specific replacements will be ignored (the function is looked up in global scope). Otherwise, if T is a class type, lookup begins in the class scope of T.

因此类特定的 new 具有优先权。

关于+的重载,可以是成员重载或者全局重载(通常作为类的friend)但不是两者都是因为它产生的歧义。

关于c++ - 为什么覆盖全局新运算符和类特定运算符不是模棱两可的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52554571/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com