【发布时间】:2021-06-23 03:53:19
【问题描述】:
struct myclass{
static const int invalid = -1;
/*explicit*/ myclass(int i, double d = 0.0){
_var = i
}
int _var;
bool operator < (const myclass& rhs);
bool operator > (const myclass& rhs);
bool operator == (const myclass& rhs);
bool operator != (const myclass& rhs);
/*
bool operator == (int rhs){
return *(this) == myclass(rhs); // Is this valid C++ ?
}
bool operator != (int rhs){
return *(this) == myclass(rhs); // Is this valid C++ ?
}
*/
};
int userCodeCall() {
myclass m(10);
// Valid use Case
if(m != myclass::invalid) {
//.... do something
}
// Invalid use case
if(m < 0.5) { // I want this to give me a compiler error
//.... do something
}
// Invalid use case
if(m < 5) { // I want this to give me a compiler error
//.... do something
}
}
我正在处理一个遗留代码库,我遇到了一个可以从 int 隐式构造的类。我发现了一个错误,我们正在执行
bool operator == (int rhs){
return *(this) == myclass(rhs); // Is this valid C++ ?
}
我有两个问题?
-
C++11/14/17 有效吗?
-
课程的设计可以改进吗?鉴于我仍然希望使用“==”比较样式来保持有效,因为它遍布用户代码库。
if(m != myclass::invalid) // some similar API need to be supported, if not the same.
【问题讨论】:
-
我把变量名弄乱了。可以说它是_var。我也在用例中使用 != 并在类中定义了 == 运算符。我在用例中需要它们。所以,假设我也在类中定义了它们。,
-
请通过编辑问题添加所有澄清和更正,而不是离开 cmets。
-
创建无效
this指针的唯一方法是让调用代码或以前的代码表现出未定义的行为(例如取消引用NULL、从悬空指针创建引用等)。