我有一个类测试引用的默认构造函数。
class test {
public:
test(int &input1) : int_test(input1) {};
~test() {};
int & int_test;
};
然后再有2个与test交互的类,如下所示:
class notebook
{
public:
notebook() {};
~notebook() {};
int int_notebook;
};
class factory
{
public:
factory() {};
~factory(){};
notebook *p_notebook;
};
如果我使用整数初始化测试(t2),则可以按预期工作:
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
一旦我通过第三类工厂使用指向类笔记本成员的指针初始化了测试类:
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
但是,如果我将f1.p_notebook的指针更改为笔记本s2的另一个对象;
f1.p_notebook=&s2;
cout<<t1.int_test; // This gives 10
t1的a的引用成员(t1.int_test)不反映指针的变化。 有人可以向我解释为什么吗? 或者我在这里做错了。