Re: How to use operator overloading?
"osmium" <r124c4u102@comcast.net> ha scritto nel messaggio
news:7rh57oFoa8U1@mid.individual.net...
#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.
what about this?
#include <iostream>
using namespace std;
class intc{
public:
int datum;
intc() {}
intc(int a){datum=a;}
void show() {cout << "intc datum: " << datum << endl;}
intc operator+(intc rhs) {return datum+rhs.datum;}
intc& operator-(intc& rhs);
friend ostream& operator<<(ostream& ost, intc& b)
{ost << b.datum << flush; return ost;}
};
unsigned index=0;
intc v[16];
intc& intc::operator-(intc& rhs)
{unsigned u;
v[u].datum=datum-rhs.datum;
++index; if(index==16) index=0;
return v[u];
}
int main(void)
{intc a(7), b(5), c, n(3);
cout << a << "+" << b << "-" << n << "=";
c=a+b-n; // default operator= is perfectly
// adequate for a shallow copy situation like this
cout << c << "\n";
cin.get(); // crutch for my compiler
return 0;
}