Re: How to use operator overloading?
Immortal Nephi wrote:
On Jan 16, 7:05 pm, "osmium" <r124c4u...@comcast.net> wrote:
"Immortal Nephi" wrote:
<elided stuff>
test& operator+( const test &r )
{
return *this;
}
};
Shouldn't the code for a function that adds have a '+' someplace in
the code?
Is there an extra brace? Please post code that you compile, not
simply code produced by the same set of fingers. We call it "cut and
paste".
test& operator+( const test &r )
{
return *this;
}
};
I am asking. How can left object and right object be prevented from
doing addition. Only "left object += right object" and "left object =
left object + right object" are allowed.
Look at operator+ function below. I don't know how to write my code
in the operator+ function body. I do know how to do addition.
test& operator+=( const test &r )
{
this->x += r.x;
return *this;
}
test& operator+( const test &r )
{
this->x += r.x; // How to prevent addition?
return *this;
}
Another example does the same to string like below.
string s1 = "A", s2 = "B";
s1 + s2; // prevent from doing addition
s1 += s2; // s1 = "AB"
s1 = s1 + s2; // s1 = "ABB"
I hope I can explain clear. Thanks...
I think you are trying to go too fast. For examaple, you had a destructor
in your earlier post, there is no reason at all to provide one. It makes me
wonder: Do you know what a destructor *does*? Do you understand shallow
copy, deep copy?
As far as I can tell, you expect the compiler to know how to add two
things - it doesn't work that way. First of all, provide some data to add.
And then tell the compiler, via code, how to add those things. Like this:
#include <iostream>
using namespace std;
class INT
{
public:
INT() {}
INT(int a) { datum = a;}
void show() {cout << "INT datum: " << datum << endl;}
INT operator+(INT rhs) { return datum + rhs.datum;}
private:
int datum;
};
int main()
{
INT a(7), b(5), c;
a.show();
b.show();
c = a + b; // default operator= is perfectly
// adequate for a shallow copy situation like this
c.show();
cin.get(); // crutch for my compiler
}
Get the fundamentals straight, THEN you can worry about const correctness,
reference vs. value, etc.