【发布时间】:2016-01-08 11:10:58
【问题描述】:
我正在玩重载运算符。
当我使用 INTEGER 和 STRING 类时,一切运行良好。
class INTEGER {
private:
int iValue;
public:
INTEGER() {
iValue = 0;
}
int& operator= (int const& iParam) {
return iValue = iParam;
}
friend ostream& operator<< (ostream& os, const INTEGER& obj) {
return os << obj.iValue << endl;
}
operator int () const {
return iValue;
}
operator string () const {
ostringstream os;
os << iValue;
return string(os.str().c_str());
}
};
class STRING {
private:
string strValue;
public:
STRING () {
strValue = "";
}
string& operator= (string const& strParam) {
return strValue = strParam;
}
friend ostream& operator<< (ostream& os, const STRING& obj) {
return os << obj.strValue.c_str() << endl;
}
operator int() const {
istringstream ss(strValue);
int iValue;
ss >> iValue;
return iValue;
}
};
int main() {
INTEGER i1, i2;
STRING s1, s2;
i1 = 1;
s1 = "2";
i2 = i1 + s1;
s2 = i2;
cout << i1 << s1 << i2 << s2;
return 0;
}
输出:
1 2 3 3
但是如果我用
扩展我的类 INTEGERoperator double () const {
return (double)iValue;
}
(为下一堂FLOAT做准备)
编译器在“operator INTEGER::int() const”和“operator INITEGER::double() const”之间不明确
i2 = i1 + s1;
我不懂我的编译器,从未使用过浮点值。 i1 和 i2 来自 INTEGER 类,s2 来自 STRING 类,并且有一个 int()- 运算符。
请点亮我的心灵...
【问题讨论】:
-
int& operator= (int const& iParam) { iValue = iParam; }您没有返回值,因此行为是未定义。 -
你确定它说的是“INTEGER::init”而不是“INTEGER::int”吗?我认为您的问题是,如果没有双重运算符,您的代码是:
i2.operator=(i1.operator int() + s1.operator int());。使用双重运算符,它无法决定是否使用它,或者i2.operator=(static_cast<int>(i1.operator double() + static_cast<double>(s1.operator int())); -
这就是 C++ 社区中许多人回避强制转换运算符的原因。假设您的代码确实编译了。首先,正如所指出的,由于未从声明为返回值的函数返回值,因此行为未定义。但其次,您能否确定在运行程序时将调用哪个运算符,即不使用调试器?这就是问题所在——使用强制转换运算符的代码多次调用我们不希望调用的函数。