为什么通过指针完成引用会中断

时间:2011-12-11 21:30:33

标签: c++ pointers reference class-design

我有一个类测试的引用默认构造函数。

class test {
public:
    test(int &input1) : int_test(input1) {};
    ~test() {};

    int & int_test; 
}; 

然后又有2个与测试相互作用的类如下:

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= &notebook::int_notebook;
f1.p_notebook=&s1;

test t1(((f1.p_notebook->*p_notebook)));
cout<<t1.int_test; // This gives  10

但是,如果我将f1.p_notebook的指针更改为notebook s2的另一个对象;

f1.p_notebook=&s2;
cout<<t1.int_test; // This gives  10

t1(t1.int_test)的a的引用成员不反映指针的变化。有人可以向我解释原因吗?或者我在这里做错了什么。

2 个答案:

答案 0 :(得分:0)

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 = &notebook::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;
}

打印

10
2

答案 1 :(得分:0)

您的班级test引用了一个int。它对int实际所属的对象一无所知。或者它最初如何访问该int。让我们分解这行代码:

test t1(((f1.p_notebook->*p_notebook)));

首先:

f1.p_notebook

从该行开始,它是指向s1的指针。现在这个:

f1.p_notebook->*p_notebook

那是s1的int_notebook成员。所以:

test t1(((f1.p_notebook->*p_notebook)));

您正在将s1的int_notebook成员传递给test的构造函数。所以现在对象t1引用了s1的int_notebook成员。它并不关心你用来获得该成员的间接模糊程度。它[t1]对f1或f1.p_notebook一无所知。所以当你这样做时:

f1.p_notebook=&s2;

这对s1.int_notebook完全没有影响,因此它对t1的引用成员没有影响。