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

发布于 2024-12-09 13:15:16 字数 803 浏览 0 评论 0原文

在 GCC 以后的版本中。当一个人有多个采用引用或指针的构造函数时,如何(如果可以的话)消除“0”或“NULL”的歧义?

IE:

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.

In GCC later versions. How can one (if one can) disambiguate '0' or 'NULL' when one has multiple constructors that take references or pointers ?

ie:

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

酒几许 2024-12-16 13:15:16

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++ has a type system, so variables have types, which are used by the compiler to perform overload resolution:

const char * p = 0;
const AnotherThing * q = 0;

XXX a(p), b(q); // uses the respective constructors for the static type of p, q

If the overload is ambiguous because you don't use one of the required pointer types, you'll get an error:

XXX c(0); // error: ambiguous
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文