类中的强制转换运算符和std :: string出错

时间:2014-11-20 18:36:51

标签: xcode c++11 operator-overloading

我在以下问题中解决了我已经尝试解释here的问题:

#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似乎有几个甚至覆盖int的构造函数。我有一个类需要转换为std :: string,但也是一个整数类型。由于assign(=)运算符不能在类定义之外覆盖,我不知道如何运行上述程序。 这是糟糕的设计,但值得注意的是,VS2013对上述代码没有任何问题。

1 个答案:

答案 0 :(得分:1)

您可以使用explicit conversion

explicit operator std::string()
~~~~~~~
{
    return std::string("Huhuhu");
}
相关问题