Hi,
I can overload the + operator as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
#include <iostream>
using namespace std;
class CVector
{
public:
int x, y;
CVector() {};
CVector(int a, int b) : x(a), y(b) {}
CVector operator + (const CVector&);
};
CVector CVector::operator+ (const CVector& param)
{
CVector temp;
temp.x = x + param.x;
temp.y = y + param.y;
return temp;
}
int main()
{
CVector foo(3, 1);
CVector bar(1, 2);
CVector result;
result = foo + bar;
cout << result.x << ',' << result.y << '\n';
cout << endl;
cout << "Press any key to exit.";
cin.get();
}
|
However, I am trying something else and having problems. I know this is weird but I have a class with two string members; in my +operator overload, I want to return a class object for which one of the strings gets its value from the first operand and the other string gets its value from the second operand.
Obj1: rider = Jane, horse = Rosie, Obj2: rider = Ian, horse = Ben
Obj3 = Obj1 + Obj2 : rider = Jane, horse = Ben
Here's my code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
#include <iostream>
using namespace std;
class Team
{
string rider;
string horse;
public:
Team();
Team(string ridername, string horsename);
void setRider(string name) { rider = name; }
void setHorse(string name) { horse = name; }
string getRider() { return rider; }
string getHorse() { return horse; }
Team operator + (const Team&);
};
Team Team::operator+ (const Team& team2)
{
Team temp{};
temp.setRider(team2.getRider());
temp.setHorse(horse);
return temp;
}
Team::Team(string ridername, string horsename)
{
rider = ridername;
horse = horsename;
}
int main()
{
Team USA("Felicity", "Rosie");
Team Canada("Ian", "Big Ben");
Team Combined = USA + Canada;
cout << endl;
cout << "Press any key to exit.";
cin.get();
}
|
I get 2 errors I don't know what to do about:
Error 1 error C2662: 'std::string Team::getRider(void)' : cannot convert 'this' pointer from 'const Team' to 'Team &' c:\users\felicity\dropbox\c++\tutorial\024advanced_class\advanced_class.cpp Line 25 1 024Advanced_class
Error 2 IntelliSense: the object has type qualifiers that are not compatible with the member function object type is: const Team c:\Users\Felicity\Dropbox\C++\Tutorial\024Advanced_class\Advanced_class.cpp Line 25 16 024Advanced_class
Any help would be appreciated :)