如何将指向基类的指针保存到另一个类的字段?

时间:2014-12-14 20:58:27

标签: c++ pointers

我的项目中有4个类:Base,Derived1,Derived2和另外一个,例如MyClass。

我想要一个像这样的构造函数

MyClass(Base *_p){p = _p};

p是指向Base类的指针,但它实际上是指向Derived1或Derived2的指针。 保存指向字段的指针是不安全的:可以从main.cpp重写它,我的程序将崩溃。我的意思是:

Base *h = new Derived1();
MyClass d1 = MyClass(h);
*h = Derived2;
d1.run();

如果我们将h保存到MyClass的一个字段,那么当我们执行d1.run()时,它将是奇怪的(我们将使用Derived2的重载方法而不是Derived1)。在d1.run()中使用了Base的一些重载方法,例如p-> insert(),它在Derived1和Derived2中是不同的。

所以,我想知道,在这种情况下我应该怎么写程序?

P.S。我仍然需要帮助。

1 个答案:

答案 0 :(得分:0)

如果我找对你,你会得到像

这样的东西
struct Base { 
             virtual void run () = 0; 
             virtual ~Base() {} };
struct Derived1 : Base { void run () { /* do Stuff A */ } };
struct Derived2 : Base { void run () { /* do Stuff B */ } };
struct MyClass { Base * p;
                MyClass (Base * _p) { p = _p; } };

Wehen您使用d1.run()时,您将看不到调用Derived2的方法。

Base *h = new Derived1();
MyClass d1 = MyClass(h); 
h = new Derived2(); // you change h here not d1.p !
// At this point d1.p is still the same value as above 
// pointing to the originally created Derived1 object
d1.run(); // will execute do Stuff A

<小时/> 编辑:

*h = Derived2; // Assignment

此分配仅在Derived1定义

时有效
  • 构造函数Derived1 (Derived2 (const) &d2) { /*...*/}
  • 赋值运算符Derived1& operator= (Derived2 (const) &d2) { /*...*/ }

如果是这种情况,并且您的主程序有任何有效的引用或指向结构d1.p的指针,那么它当然可以操纵逻辑。