gpt4 book ai didi

c++ - 定义赋值运算符= 只允许零 rhs,否则不会编译

转载 作者:行者123 更新时间:2023-11-30 00:40:08 36 4
gpt4 key购买 nike

简而言之:
我如何为我的类定义 operator= 以便它仅在 rhs 为 0 (obj = 0) 时编译
但如果 rhs 为非 0 值,则会出现编译错误。
我知道这是可能的,忘了怎么做。

更长:
我有 C 类。我想允许为此类的对象赋值 obj = 0(这意味着重置对象),但是没有定义来自其他整数或指针的赋值。除了 obj=0 之外,没有定义从整数或从指针的转换。

C obj;
obj = 0; // reset object

operator= 中,我可以执行 assert(rhs == 0),但这还不够好。
我知道这是可能的定义 operator= 这样
如果 rhs 不为 0,它会给出编译错误。忘记了细节。
有人可以补充吗?

谢谢

最佳答案

使用指向成员的指针:

class foo
{
// Give it a meaningful name so that the error message is nice
struct rhs_must_be_zero {};

// The default operator= will still exist. If you want to
// disable it as well, make it private (and the copy constructor as well
// while we're at it).

foo(const foo&);
void operator=(const foo&);

public:
foo& operator=(int rhs_must_be_zero::*) { return *this; }
};

由于您无法访问 foo::rhs_must_be_zero,因此您无法命名指向此类成员的指针。您可以命名的唯一指向成员的指针是空指针,也就是字面量零。

演示在 http://ideone.com/bT02z

关于c++ - 定义赋值运算符= 只允许零 rhs,否则不会编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6849921/

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