相关疑难解决方法(0)

在构造函数中调用虚函数

假设我有两个C++类:

class A
{
public:
  A() { fn(); }

  virtual void fn() { _n = 1; }
  int getn() { return _n; }

protected:
  int _n;
};

class B : public A
{
public:
  B() : A() {}

  virtual void fn() { _n = 2; }
};
Run Code Online (Sandbox Code Playgroud)

如果我写下面的代码:

int main()
{
  B b;
  int n = b.getn();
}
Run Code Online (Sandbox Code Playgroud)

人们可能期望将n其设置为2.

事实证明,n设置为1.为什么?

c++ constructor overriding virtual-functions

220
推荐指数
6
解决办法
9万
查看次数

构造函数的C++虚函数

为什么以下示例打印"0"以及必须更改它以打印"1",如我所料?

#include <iostream>
struct base {
   virtual const int value() const {
      return 0;
   }
   base() {
      std::cout << value() << std::endl;
   }
   virtual ~base() {}
};

struct derived : public base {
   virtual const int value() const {
      return 1;
   }
};

int main(void) {
   derived example;
}
Run Code Online (Sandbox Code Playgroud)

c++ oop virtual constructor class

57
推荐指数
3
解决办法
4万
查看次数

标签 统计

c++ ×2

constructor ×2

class ×1

oop ×1

overriding ×1

virtual ×1

virtual-functions ×1