c++ - 可以为多个构造函数消除 0 (NULL) 的歧义吗?和赋值运算符?

标签 c++ gcc compilation

在 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/

相关文章:

c++ - C++中while循环执行中的printout语句

声明为静态类成员的 C++ 类

gcc - c - 将支持 PGI OpenACC 的库与 gcc 链接

ubuntu - 无法在 Ubuntu 上编译委托(delegate)

java - java编译器如何找到没有头文件的类?

c++ - 尝试使用 const int std::array 时出错

c# - 覆盖基类方法

c - 结构大小问题,要求不需要的内存?

gcc - gcc -march选项的默认设置是什么?

c++ - 部分 C++ 程序的静态分析