0

How can I perform this code with below details in C++:

mystring a;
a="A test text";

"mystring" is a class that is defined (by myself) for strings , and other operators like + , == , >> , << , etc are defined in this class. How can i define a function (a friend function with class) that "=" perform something that I have mentioned.

if there were dictation mistakes, forgive me.

  • 2
    The same way it is done in STL? http://www.cplusplus.com/reference/string/string/operator=/ – myaut Apr 16 '15 at 07:29
  • Don't create own string classes, use `std::string`. – Griwes Apr 16 '15 at 07:34
  • Good answers below, but once you've built your string class, look through it carefully, compare it with `std::string`, bin the former, and use the latter. – Bathsheba Apr 16 '15 at 07:36

2 Answers2

2

You need to define

mystring& operator=(const char*)

for this specific assignment to work.

Note that this overload returns a reference to self. This allows for compound assignments.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

Not with a friend function. You need to overload the assignment operator :

mystring &operator = (mystring const &other) {
    // ...
    return *this;
}

Note that you'll also need a conversion constructor that takes in a C-string :

mystring(char const *str) {
    // ...
}
Quentin
  • 62,093
  • 7
  • 131
  • 191
  • 1
    If there was a `mystring(const char *)` ctor (which is a safe assumption), wouldn't that obviate the need for a special `mystring::operator=(const char *)`? Efficiency issues aside. – Peter - Reinstate Monica Apr 16 '15 at 07:35
  • @PeterSchneider Wait, I read your comment wrong three times in a row. There's no assignment operator from `char const*` here :) – Quentin Apr 16 '15 at 07:44
  • Oh. Right! You suggested what I was thinking, too. I need to ask that question to @Bathsheba who suggested a `mystring::operator=(const char *)`. – Peter - Reinstate Monica Apr 16 '15 at 08:11