简体   繁体   中英

Direct Assignment Operator in C++

I'm playing with operator overloading in C++, specifically the assignment operator "=".

So, at a time, I'm able to do this:

MyClass var1;
var1 = "string";

But, it gives me an error when I try to do this:

MyClass var2 = "string";

Somebody knows why? And how can I make it possible?

The second example isn't calling operator= , it's calling a conversion constructor for const char [] , or whatever you'd be using it for internally, as long as it can convert from that (eg std::string ), which doesn't exist as of yet. You can see one implemented in std''OrgnlDave's answer. It's almost identical to

MyClass var2 ("string");

The latter, though, is explicit, whereas the former is implicit. To see the difference, make a constructor and mark it explicit . The code here will work, but yours won't. This can save confusion when you, for example, pass a string by accident instead of a MyClass , and it gets implicitly converted when it isn't even meant to be a MyClass in the first place.

You need to make a constructor for your class, the second example is calling the constructor.

class MyClass {
  public:
    MyClass(const std::string& what) {  } // copy string
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM