c ++,更改另一个类中对象的指针

时间:2015-10-06 10:13:32

标签: c++ function class pointers

我需要更改类中对象的指针。 在这个例子中,我想从b b-> getBase()的成员函数调用;在主要打印值2,而不是1。

int main(int argc, char *argv[])
{
base *b = new base(1);
top *t = new top( b);
b->getBase();
return 0;
}

base.h

class base
{
public:
    base(int _x);
    void getBase();
private :
    int x;
};

base.cpp

base::base(int _x):x(_x)
{
cout <<"base constructor:"<<x<<":";
};

void base::getBase()
{
cout <<"getBase()"<< x<< endl;
}

top.h

class top
{
public:
    top(base *b);
private:
    int topVar;
    base * b;
};

top.cpp

top::top(base * _b):b(_b)
{
    b->getBase();
    b = new base(2);
    b->getBase();
}

结果:     基础构造函数:1     getBase():1     基础构造函数:2     getBase():2     getBase():1

0 个答案:

没有答案