Trouble with defining my own operator...
I'm just toying around to watch how defining operators work. The following code gives me an error about "No candidate functions found".
Any criticism other than that of the root cause is welcome, too. Thanks!
#include <iostream>
using std::cout; using std::cin; using std::endl;
using std::string;
class SomeClass {
public:
SomeClass(int newNum, string newString) { num=newNum; str = newString; }
SomeClass& operator=(const SomeClass& rh) {
string newVal(rh.getStr());
str = newVal;
}
void setStr(string newString) { str = newString; }
const string getStr() { return str; }
string toString() { return str+str; }
private:
string str;
int num;
};
int main() {
SomeClass a(5, "five");
SomeClass b(3, "three");
开发者_如何学C cout << a.toString() << endl << b.toString() << endl;
a=b;
cout << a.toString() << endl << b.toString() << endl;
}
const string getStr() { return str; }
should be
const string& getStr() const { return str; }
Otherwise you cannot call a non-const function on a const parameter of
SomeClass& operator=(const SomeClass& rh)
Note that private, public and protected visibility is at class level, not instance level. So there is no need for a getStr()
function. You could write:
SomeClass& operator=(const SomeClass& rh) {
this->str = rh.str;
return *this;
}
Everything looks fine so far except that you've not included
#include <string>
You need to include this as well.
Oh I also saw that you're not returning anything from the function:
SomeClass& operator=(const SomeClass& rh) {
string newVal(rh.getStr());
str = newVal;
return *this; //DO THIS AS WELL
}
And also, rh
is a const object in this function and using it, you're calling getStr()
which is a non-const function which is causing the problem. So the fix is this:
const string getStr() const { return str; }
// ^^^^^ make the function const!
And alternatively, you could've written your operator=
as follows:
SomeClass& operator=(const SomeClass& rh) {
str = rh.str; //no need to create a local (temporary) variable!
return *this; //DO THIS AS WELL
}
I think its better solution!
You just need to change
const string getStr() { return str; }
to
const string getStr() const { return str; } //the 2nd const make getStr() a const member function
^^^^
This is because const object can only call const member function and you were trying to doing this:
SomeClass& operator=(const SomeClass& rh) { //here you declared rh to be const
//so in order to call getStr() from rh, you need declare getStr function to be const
string newVal(rh.getStr());
str = newVal;
return *this;
}
So your class could simply look like this:
class SomeClass {
public:
SomeClass(int newNum, string newString):num(newNum), str(newString) {/* Empty */}
SomeClass& operator=(const SomeClass& rh) {
str=rh.str;
return *this;
}
string toString() { return str+str; }
private:
string str;
int num;
};
精彩评论