class test {
public:
test operator= (const test &t) {
a = t.a;
b = t.b;
//my question is, "who" is the pointer?
return *this;
}
private:
int a, b;
};
int main () {
test a, b;
//if there's operation like this
a = b;
cout << a;
getch();
return 0;
}
"this" is a predefined pointer which points to private members of the class and the program you wrote make no sense ........
That's not correct. The this pointer points to the object itself, not to its members. You can use it to refer to a member (this->a), but it's not necessary (you could just say a). And the program does make sense, although those members could use some initialization.
#include <iostream>
class test {
public:
staticint globalCounter;
//You are supposed to run this test twice.
//Once with the below line turned on, and once with the below line commented out.
test(const test& t) { this->globalCounter++; };
test operator= (const test &t) {
this->a = t.a;
this->b = t.b;
return *this;
};
test(){this->globalCounter++;};
private:
int a, b;
};
int test::globalCounter=0;
int main()
{ test a;
test b;
a.operator=(b);
std::cout << "Number of test objects created: " << test::globalCounter << std::endl;
return 0;
}
On gcc compiler:
1) the code as it is will produce answer 3.
2) the code with the indicated line commented out will produce answer 2.
That's what is happening in the "test operator= (const test &t)" function. You can do the same with the << and in the implementation you can individually cout each data field. That way you can just cout an instance of a class easily in your program.
i can understand that, but in this case, a is not a pointer.
You're mixing up objects and pointers to objects. this always points to the object a member function has been called with.
With
1 2 3
test *a, b;
a = &b;
a->somefunction(b);
a points to b and in somefunction, this also points to b.
b is an actual test object, whereas a just points to a test object. When you dereference a, you get a reference to b.
With this:
1 2
test a, b;
a = b;
operator= is called on a, so "this" points to a inside operator=.