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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
#include <iostream>
using namespace std;
//#define friends
#define members
//in header
class Object {
static int temp_objectCounter;
int x;
const char identity;
public:
Object(int xx = 0, const char c=' ') : x(xx), identity(c) {
if (identity != ' ') printf("Object %c created\n", identity);
else printf("Object temporary_%d created\n", ++temp_objectCounter);
}
Object(const Object& obj) : x(obj.x), identity('n') { cout << "copy constructor called\n";}
~Object() {
if (identity != ' ') printf("Object %c destroyed\n", identity);
else printf("Object temporary_%d destroyed\n", temp_objectCounter--);
}
#ifdef friends
friend const Object
operator+(const Object& left,
const Object& right);
#endif
#ifdef members
Object operator+ (const Object& right);
#endif
void print();
};
//-----
//in class file------------------------
int Object :: temp_objectCounter = 0;
#ifdef members
inline Object Object::operator+ (const Object& right) {
printf("%c & %c called to perform %d + %d\n", identity, right.identity, x, right.x);
return x + right.x;
}
#endif
#ifdef friends
const Object operator+ (const Object& left, const Object& right) {
printf("%c & %c called to perform %d + %d\n", left.identity, right.identity, left.x, right.x);
return left.x + right.x;
}
#endif
inline void Object::print() {
printf("value of %c is %d\n", identity, x);
}//-------------------------------------
int main() {
Object a(2, 'a'), b(8, 'b'), c(32, 'c');
Object n = a + b + c;
n.print();
}
|