【发布时间】:2018-10-02 19:18:46
【问题描述】:
我有一个类有一个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";
}
【问题讨论】:
-
请在stackoverflow.com/questions/4421706/…阅读问题的答案。这可能会帮助您解决问题。
-
这不是赋值,而是初始化。你需要一个构造函数。
-
你试过
strtype(const string& ss) {吗?
标签: c++ class oop operator-overloading