在 GCC 以后的版本中。当一个人有多个采用引用或指针的构造函数时,如何(如果可以)消除“0”或“NULL”的歧义?
即:
class XXX
{
public:
XXX(const XXX &tocopy);
XXX(const char *fromAString);
XXX(const AnotherThing *otherThing);
operator=(const XXX &tocopy);
operator=(const char *fromAString);
operator=(const AnotherThing *otherThing);
};
// nice not to have to cast when setting to NULL for
// things like smart pointers and strings. Or items that can be initialized from
// several types of objects and setting to null means "clear"
XXX anXXX = NULL;
anXXX = 0;
// In MSC one can have an
// XXX(const int &nullItem) { DEBUG_ASSERT(!nullItem); setnull(); }
// and the overloads would be disambiguated. GCC will cause a const int to conflict
// with pointer types.
最佳答案
C++ 有一个类型系统,所以变量有类型,编译器使用这些类型来执行重载决议:
const char * p = 0;
const AnotherThing * q = 0;
XXX a(p), b(q); // uses the respective constructors for the static type of p, q
如果由于您没有使用其中一种必需的指针类型而使重载不明确,您将得到一个错误:
XXX c(0); // error: ambiguous
关于c++ - 可以为多个构造函数消除 0 (NULL) 的歧义吗?和赋值运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7747418/