假设我有两个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.为什么?
在以下示例中,我收到了 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)