所以我有一个类似于这个的类:
class CVal {
public:
void operator=(int n) {
d = n;
}
private:
int d;
};
现在每当我做类似的事情
CVal c;
switch(c) {...}
我想访问 CVal::d,那么我该怎么做呢?我想重载一些运算符,但找不到任何东西。
最佳答案
你应该这样定义转换运算符
class CVal {
public:
//...
operator int() const { return d; }
private:
int d;
};
或者,如果您有一个支持 C++ 2014 的编译器,那么您可以按以下方式定义它
class CVal {
public:
//...
operator auto() const { return d; }
private:
int d;
};
根据C++标准(6.4.2 switch语句)
2 The condition shall be of integral type, enumeration type, or class type. If of class type, the condition is contextually implicitly converted (Clause 4) to an integral or enumeration type. Integral promotions are performed....
关于C++ 使用类作为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31143642/