问题
i have a referenced default constructor for a class test.
class test {
public:
test(int &input1) : int_test(input1) {};
~test() {};
int & int_test;
};
Then 2 more classes which interact with test as follows:
class notebook
{
public:
notebook() {};
~notebook() {};
int int_notebook;
};
class factory
{
public:
factory() {};
~factory(){};
notebook *p_notebook;
};
If i intitalise test (t2) with an integer, this works as expected:
int _tmain(int argc, _TCHAR* argv[]){
int var=90;
test t2(var);
cout<<t2.int_test; // this gives 90
var=30;
cout<<t2.int_test; // this gives 30
Once i initialised the test class with a pointer to a member of class notebook through a third class factory:
factory f1;
notebook s1;
notebook s2;
s1.int_notebook=10;
s2.int_notebook=2;
int notebook::*p_notebook= ¬ebook::int_notebook;
f1.p_notebook=&s1;
test t1(((f1.p_notebook->*p_notebook)));
cout<<t1.int_test; // This gives 10
however if i change the pointer of f1.p_notebook to another object of notebook s2;
f1.p_notebook=&s2;
cout<<t1.int_test; // This gives 10
the reference member of a of t1 (t1.int_test) doesnt reflect the change of the pointer. could some one explain to me why ? or what i'm doing wrong here.
回答1:
class CTester
{
public:
CTester(int &input1) : int_test(input1)
{
std::cout << int_test << std::endl;
}
int &int_test;
};
class notebook
{
public:
int int_notebook;
};
class factory
{
public:
notebook *p_notebook;
};
int main()
{
factory f1;
notebook s1;
notebook s2;
s1.int_notebook=10;
s2.int_notebook=2;
int notebook::*p_notebook = ¬ebook::int_notebook;
f1.p_notebook=&s1;
CTester t1(f1.p_notebook->*p_notebook);
f1.p_notebook=&s2;
CTester t2(f1.p_notebook->*p_notebook);
return 0;
}
this prints
10
2
回答2:
Your class test
has a reference to an int. It doesn't know anything about what object that int actually belongs to. Or how it originally got access to that int. Let's break down this line of code:
test t1(((f1.p_notebook->*p_notebook)));
First this:
f1.p_notebook
As of that line, it is a pointer to s1. Now this:
f1.p_notebook->*p_notebook
That's s1's int_notebook
member. So with this:
test t1(((f1.p_notebook->*p_notebook)));
You are passing s1's int_notebook
member to the constructor of test. So now the object t1
has a reference to s1's int_notebook
member. It does not care about the obscure levels of indirection you used to get that member. It[t1] knows nothing of f1, or f1.p_notebook. So when you do this:
f1.p_notebook=&s2;
That has absolutely no effect on s1.int_notebook, and therefore it has no effect on t1's reference member.
来源:https://stackoverflow.com/questions/8467640/why-does-referencing-break-when-done-through-pointers