相关疑难解决方法(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万
查看次数

类中的抽象属性不能在构造函数中访问

在以下示例中,我收到了 TypeScript 错误 Abstract property 'name' in class 'Minigame' cannot be accessed in the constructor.

我正在努力思考如何实现这一点。我无法将具体类的名称传递到super()调用中,因为在调用之前我无法访问对象的属性,并且我无法创建属性,static因为抽象类无法强制执行。

这应该如何组织以保证每个Minigame实例化一个Explanation对象,这需要具体类的 name 属性?使名称static(并删除抽象要求)真的是保持简单的最佳选择吗?

abstract class Minigame {
    abstract name: string;
    explanation: Explanation;

    constructor() {
        this.explanation = new Explanation(this.name);
    }
}

class SomeGame extends Minigame {
    name = "Some Game's Name";

    constructor() {
        super();
    }
}
Run Code Online (Sandbox Code Playgroud)

abstract-class typescript

7
推荐指数
2
解决办法
3127
查看次数