c++ - 异构列表、虚函数和成员数据

标签 c++ inheritance virtual heterogeneous

在通过异构列表调用虚函数时,我在弄清楚如何为成员数据赋值时遇到了一些麻烦。

这是我正在尝试做的一个例子:

class A
{
 protected:
 virtual void func1();

 private:
 A * list;
}

class B: public A
{
 protected:
 void func1();

 private:
 int i1, i2;
}

在 main() 中:

list = new A[10];

list[0] = new B;

list[0]->Func1();

Func1() 的声明:

void B::Func1()
{
 int a, b;

 cin >> a >> b;

 list[0]->i1 = a;
 list[0]->i2 = b;

 // or can I just do this:
 // i1 = a;
 // i2 = b;
}

如果通过父类的指针从 main 调用,我正在寻找在派生类的函数中访问派生类的成员数据的适当方法。任何帮助将不胜感激!

最佳答案

当执行一个virtual 函数时,您现在对象的类型是定义该函数的类的类型或派生类的类型。也就是说,在您的 B::func1() 函数中,您知道 this 指向一个 B 对象。该对象可能是从 B 派生的类型,但您仍然拥有 B 中的所有内容。

另一方面,您静态地知道list[0] 指向B 对象。您在代码中取消注释的代码不起作用。注释的代码看起来不错

关于c++ - 异构列表、虚函数和成员数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20009850/

相关文章:

c++ - 在 Ubuntu 12.10 上不能包含 "linux/in6.h"而没有错误

c++ - 多态覆盖

Haskell 继承 : What's inherity about it?

c++ - 重新编译二进制或派生类以在基类中添加新方法

c++ - 多站点执行 : Getting rid of virtual table with inheritance (legacy code)

c++ - 薄与厚适配器(包装器)示例

c++ - 为什么 deque 的 pop_front() 和 pop_back() 不是 noexcept?

c++ - std::map<struct, int> 我需要析构函数吗?

Python 多态性

C++ 指向派生类对象的基类指针不调用派生等于运算符函数