Xcode 类中的强制转换运算符和std::string出错
我分解了一个问题,我已经尝试在以下问题中解释:Xcode 类中的强制转换运算符和std::string出错,xcode,c++11,operator-overloading,Xcode,C++11,Operator Overloading,我分解了一个问题,我已经尝试在以下问题中解释: #include <iostream> #include <string> class atest { public: operator std::string() { return std::string("Huhuhu"); } operator int() { return 42; } }; int main(int argc, cha
#include <iostream>
#include <string>
class atest
{
public:
operator std::string()
{
return std::string("Huhuhu");
}
operator int()
{
return 42;
}
};
int main(int argc, char* argv[])
{
atest tst;
std::string astr;
astr=tst;
int i=0;
i=tst;
return 0;
}
#包括
#包括
班级考试
{
公众:
运算符std::string()
{
返回std::字符串(“Huhuhu”);
}
运算符int()
{
返回42;
}
};
int main(int argc,char*argv[])
{
atest tst;
std::字符串astr;
astr=tst;
int i=0;
i=tst;
返回0;
}
std::string似乎有几个构造函数,甚至包含int。我得到了一个类,它需要能够转换为std::string,但也可以转换为整型。由于assign(=)运算符不能超出类定义,我不知道如何运行上述程序。
这是一个糟糕的设计,但值得注意的是,VS2013对上述代码没有问题。您可以使用
explicit operator std::string()
~~~~~~~
{
return std::string("Huhuhu");
}