将字符串分配给类的实例(重载=)?

时间:2018-10-02 19:18:46

标签: c++ class oop operator-overloading

我有一类,成员类型为string。我想问一下如何使用运算符=将字符串分配给给定类的新实例化的对象。我尝试定义一个运算符,但无济于事?

class strtype {
    string str;
public:
    strtype() {
        str = "Test";
    }
    strtype(string ss) {
        str = ss;
    }
    strtype operator= (strtype &st) {
            strtype tmp;
            tmp.str = st.str;
            return tmp;
        }
};

int main(){
//how can i do the following:
strtype b = "example";
}

1 个答案:

答案 0 :(得分:0)

您的operator=的实现错误。并不是在您的示例中很重要,因为strtype b = "example";最初并未调用operator=,而是调用了strtype(string)构造函数({strtype b = "example";只是{{1 }}。

尝试以下方法:

strtype b("example");

以下是输出:

strtype(const char *)
example
strtype(const char *)
operator=(const strtype &)
something else

Live Demo

相关问题