Reading Books/Effective Series
EC++ Item 21: Don't try to return a reference when you must return an object
DWGoon
2009. 12. 5. 22:07
// Coded with Dev-C++ IDE
// When you use a static variable in the case...
#include <iostream>
using namespace std;
class Glass {
public:
Glass() { cout<< "ctor.." << endl; }
Glass(int x, int y)
{
cout<< "ctor.." << endl;
this->x = x;
this->y = y;
}
friend Glass& operator+(const Glass& lhs, const Glass& rhs);
friend bool operator==(const Glass& lhs, const Glass& rhs);
int x;
int y;
};
Glass& operator+(const Glass& lhs, const Glass& rhs)
{
static Glass g;
g.x = lhs.x+rhs.x;
g.y = lhs.y+rhs.y;
cout << "g.x : " << g.x << ", g.y: " << g.y << endl;
return g;
}
bool operator==(const Glass& lhs, const Glass& rhs)
{
return lhs.x == rhs.x && lhs.y == rhs.y;
}
int main()
{
Glass g1(1, 3);
Glass g2(1, 4);
Glass g3(2, 2);
Glass g4(2, 2);
if ((g1+g2) == (g3+g4)) {
cout << "equal" << endl;
} else
cout << "not equal" << endl;
system("pause");
return 0;
}
// When you use a static variable in the case...
#include <iostream>
using namespace std;
class Glass {
public:
Glass() { cout<< "ctor.." << endl; }
Glass(int x, int y)
{
cout<< "ctor.." << endl;
this->x = x;
this->y = y;
}
friend Glass& operator+(const Glass& lhs, const Glass& rhs);
friend bool operator==(const Glass& lhs, const Glass& rhs);
int x;
int y;
};
Glass& operator+(const Glass& lhs, const Glass& rhs)
{
static Glass g;
g.x = lhs.x+rhs.x;
g.y = lhs.y+rhs.y;
cout << "g.x : " << g.x << ", g.y: " << g.y << endl;
return g;
}
bool operator==(const Glass& lhs, const Glass& rhs)
{
return lhs.x == rhs.x && lhs.y == rhs.y;
}
int main()
{
Glass g1(1, 3);
Glass g2(1, 4);
Glass g3(2, 2);
Glass g4(2, 2);
if ((g1+g2) == (g3+g4)) {
cout << "equal" << endl;
} else
cout << "not equal" << endl;
system("pause");
return 0;
}
ctor..
ctor..
ctor..
ctor..
ctor..
g.x : 4, g.y: 4
g.x : 2, g.y: 7
equal
ctor..
ctor..
ctor..
ctor..
g.x : 4, g.y: 4
g.x : 2, g.y: 7
equal