【问题标题】:Assigning string to an instance of class (overloading = )?将字符串分配给类的实例(重载 = )?
【发布时间】: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


【解决方案1】:

您的operator= 实施错误。这在您的示例中并不重要,因为strtype b = "example"; 不首先调用operator=,而是调用strtype(string) 构造函数(strtype b = "example"; 只是strtype b("example"); 的语法糖)。

试试这个:

class strtype {
    string str;
public:
    strtype() {
        cout << "strtype()" << endl;
        str = "Test";
    }

    strtype(const strtype &st) { // <-- add this!
        cout << "strtype(const strtype &)" << endl;
        str = st.str;
    }

    strtype(const string &ss) {
        cout << "strtype(const string &)" << endl;
        str = ss;
    }

    strtype(const char *ss) { // <-- add this!
        cout << "strtype(const char *)" << endl;
        str = ss;
    }

    strtype& operator=(const strtype &st) { // <-- change this!
        cout << "operator=(const strtype &)" << endl;
        str = st.str;
        return *this;
    }

    string get_str() const { return str; };
};

int main()
{
    strtype b = "example";
    cout << b.get_str() << endl;

    b = "something else";
    cout << b.get_str() << endl;
}

这是输出:

strtype(const char *) 例子 strtype(const char *) 运算符=(const strtype &) 别的东西

Live Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 2019-02-23
    • 2012-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多