【发布时间】:2016-12-02 22:20:07
【问题描述】:
我在理解 C++ 使用隐式转换的条件时遇到了一些麻烦。假设我有一堂课:
class SomeClass
{
private:
int val;
public:
SomeClass(int i) :val{ i } {}
operator string() { return to_string(val); }
};
为什么在将此类与运算符一起使用时,我需要强制转换为字符串?为什么它不只是隐式执行转换?
代码:
int main(void)
{
SomeClass sc = 4;
cout << (string)sc << endl; //prints 4, compiles fine
cout << sc << endl;//does not compile, no operator "<<" matches these operands
string str1 = sc;//compiles fine, performs cast
string str2 = "Base String" + sc;//does not compile, no operator "+" matches these operands
}
这个问题比实际问题更具学术性,因为无论如何使用演员表更具可读性。
【问题讨论】:
标签: c++ visual-c++ operators implicit-conversion