I am currently studying operator overloading by re-reading some of my old university textbooks, and I think I misunderstand something, so I hope it will be some nice, lightweight reputation for some. responders If this is a duplicate, please point me in the right direction.
I created a simple counter class on which (at this stage) there is one member, val (int).
I initialized three of these varOne counters for varThree and want the third counter to be the sum of the first two (for example, varThree.val is set to 5 in the code below)
counter::counter(int initialVal)
{
val = initialVal;
}
int main (int argc, char const* argv[])
{
counter varOne(3), varTwo(2), varThree;
varThree = varOne + varTwo;
return 0;
}
I overloaded the + operator like this:
counter operator+(counter& lhs, counter& rhs)
{
counter temp(lhs.val + rhs.val);
return temp;
}
I made this function not a member and friend of the counter class so that it can access private values.
pVal ( int). , varThree = varOne, , varOne , varThree.pVal .
operator= .
int counter::getN()
{
return *newVal;
}
counter& counter::operator=(counter &rhs)
{
if (this == &rhs) return *this;
val = rhs.val;
delete pVal;
pVal = new int;
*pVal = rhs.getN();
return *this;
}
, - varThree = varOne, , varThree = varOne + varTwo :
counter.cpp: In function βint main(int, const char**)β:
counter.cpp:96: error: no match for βoperator=β in βvarThree = operator+(counter&, counter&)(((counter&)(& varTwo)))β
counter.cpp:55: note: candidates are: counter& counter::operator=(counter&)
make: *** [counter] Error 1
, counter::operator= operator+ operator= , , operator+, , , , , - .