简而言之:
如何为我的类定义operator =,使其仅在rhs为0(obj = 0)时
编译,但如果rhs为非0值则给出编译错误.
我知道这是可能的,忘了怎么样.
更长:
我有C类.我想允许赋值obj = 0这个类的对象(这意味着,重置对象),但是没有定义任何其他整数或指针的赋值.除了obj = 0之外,没有定义整数或指针的转换.
C obj;
obj = 0; // reset object
Run Code Online (Sandbox Code Playgroud)
在里面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; }
};
Run Code Online (Sandbox Code Playgroud)
由于无法访问foo::rhs_must_be_zero,因此无法在此类中指定指向成员的指针.您可以命名的成员唯一指针是空指针,也就是文字零.
| 归档时间: |
|
| 查看次数: |
129 次 |
| 最近记录: |