【问题标题】:can't get virtual function of parent class to work [duplicate]无法使父类的虚函数工作[重复]
【发布时间】:2018-11-05 11:43:03
【问题描述】:

我有一个包含虚函数的父类,然后我创建一个子类并定义该函数。然后我制作一个向量向量并将其中一个子类插入其中。然后我尝试调用虚函数并且没有任何输出到屏幕。我不知道为什么会这样,有人知道吗?

父类

class insect{
        public:
           string type;
           int food_cost;
           int armor;
           int damage;
           insect();
           void set_food_cost(int x);
           void set_armor(int x);
           void set_damage(int x);
           virtual void attack(){} // this is the problematic function


};

儿童班

class bee: public insect{
        public:
           bee();
           int armor;
           int damage;
           void set_armor(int x);
           void attack();


};

void bee::attack(){
        cout << "im a bee, stab stab!\n";
}

创建向量的向量

vector< vector<insect> > insects_on_board(10);

将蜜蜂添加到向量的向量中

void add_bee(vector< vector<insect> > &insects_on_board, int &bees){
        bees++;
insects_on_board[9].push_back(bee());
}

函数调用

cout << "testing " << insects_on_board.at(9).at(0).type << endl;
        insects_on_board.at(9).at(0).attack();

输出

testing B

我的问题又来了

所以在输出中我期待看到“测试 B”,然后是“我是一只蜜蜂,刺刺!”

但只有“测试B”输出到屏幕上,有什么想法为什么其他部分没有?

【问题讨论】:

  • 您可能想搜索“切片”
  • 您的载体包含昆虫,而不是蜜蜂。
  • @Sneftel 不是重复的,第一次问这个问题
  • 这个问题除了重复之外,还缺少minimal reproducible example
  • 请解释您为什么认为“4 年前的那个人没有处理我现在处理的事情”。你有点忽略了我告诉你为什么我们认为这是同一个问题的部分:“它有一个 vector&lt;BaseClass&gt; 并且 OP 希望能够在它上面调用 DerivedClass 中的虚拟方法,但是BaseClass 版本被调用。”。这怎么不是同一个问题?

标签: c++ inheritance virtual-functions


【解决方案1】:

这是因为您存储的是实际的insects,而不是任何bees。多态性(以它的基本 C++ 方式)在您做 3 件事时起作用:

  1. 拥有一个类型层次结构,其中包含正确定义和覆盖的 virtual 方法(就像您在此处所做的那样)
  2. 创建子实例(或各种父子实例)
  3. 通过指针(或引用)访问它们。

您缺少第 2 点和第 3 点。

因此,修复它的一种方法是存储指向insect 的指针,并将它们初始化为bees 或普通insects,如下所示:

vector<vector<insect *>> insects_on_board (10, vector<insect *>(2)); // note the type
insects_on_board[9][0] = new bee;
insects_on_board[9][1] = new insect;

// Note the use of "->" instead of "."
cout << "testing " << insects_on_board[9][0]->type << endl;
insects_on_board[9][0]->attack();

// Contrast the output with the above's
cout << "testing " << insects_on_board[9][1]->type << endl;
insects_on_board[9][1]->attack();

更新: 请注意,(在基本级别)任何按值存储insects 的容器都不能包含其他任何内容;甚至没有派生自insect 的类。您阅读和听到的所有多态性和内容仅适用于指向父类型和子类型(或对它们的引用)的指针

所以,您的 add_bee 函数应该如下所示:

void add_bee (vector<vector<insect *>> & insects_on_board, int & bees) {
    bees++;
    insects_on_board[9].push_back(new bee());
}

我在那里只做了两个更改:向量现在包含指向 insect 的指针,我是 newing bees。

【讨论】:

  • 好的,我在上面添加了我的 add_bee 函数,所以我相信我在你的列表中排名第二。那么是不是只有 3 号给我带来了问题?
  • @billy 不,你不是。在add_bee 中,您正在制作一个临时的bee,它被投射 到昆虫并推回您的向量中。我会更新我的答案。
猜你喜欢
  • 1970-01-01
  • 2021-01-26
  • 1970-01-01
  • 2017-12-11
  • 2021-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-22
相关资源
最近更新 更多