-1

I have a class with one member of type string. I would like to ask how can I use the operator = to assign a string to the newly instantiated object of the given class. I tried defining an operator function but to no avail?

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";
}
Y.Ivanov
  • 31
  • 1
  • 6

1 Answers1

0

Your operator= is implemented wrong. Not that it matters in your example, because strtype b = "example"; does not invoke operator= to begin with, it invokes the strtype(string) constructor instead (strtype b = "example"; is just syntax sugar for strtype b("example");).

Try this instead:

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;
}

Here is the output:

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

Live Demo

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770