小编Hyd*_*dra的帖子

添加字符串类型的类成员会导致调用基类函数而不是子类

为什么下面的代码显示0,但是如果您注释掉“ std :: string my_string”,它将显示1?

#include <stdio.h>
#include <iostream>

class A {
  public:
    virtual int foo() {
      return 0;
    }
  private:
    std::string my_string;
};

class B : public A {
  public:
    int foo() {
      return 1;
    }
};

int main()
{
    A* a;
    if (true) {
      B b;
      a = &b;
    }
    std::cout << a->foo() << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我也理解将std :: string更改为std:string *也会导致代码打印1,就像删除if语句一样,尽管我不明白为什么其中任何一个都是正确的。

快点

编辑:这似乎是由于悬空的指针。那么,在Java中执行此类操作的C ++标准模式是什么:

Animal animal; 
boolean isDog = false; 
// get user input to set isDog …
Run Code Online (Sandbox Code Playgroud)

c++ polymorphism inheritance

3
推荐指数
1
解决办法
40
查看次数

标签 统计

c++ ×1

inheritance ×1

polymorphism ×1