C++如何为抽象类中的成员变量赋予默认值?
在标头中,我定义了 bool isActive。在从这个派生的类中,我想默认将 isActive 设置为 false。我尝试通过添加
AbstractClass::isActive = false;
到 cpp 文件来执行此操作,但这会导致错误“在‘=’标记之前预期构造函数、析构函数或类型转换。”
In the header, I'm defining bool isActive. In classes derived from this one, I would like to make isActive false by default. I tried doing this by adding
AbstractClass::isActive = false;
to the cpp file, but that causes the error "Expected constructor, destructor, or type conversion before '=' token."
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在类的构造函数中对其进行初始化:
类包含抽象方法并不会阻止它拥有用于初始化其成员变量的构造函数。
Initialize it in the class' constructor:
That the class contains abstract methods doesn't stop it from having a constructor that is used to initialize its member variables.
AbstractClass::isActive = false;
指的是(不存在的)静态类成员。如果存在的话,它将作为整个类的单个共享实例存在,并且实际上您将像您所做的那样初始化它。
但是您有一个实例变量,这意味着该类的每个实例都有自己的副本。要初始化那个,你需要按照所说的去做;在类的构造函数中初始化它,可以在构造函数主体中初始化,也可以更好地在初始化列表中初始化。
AbstractClass::isActive = false;
refers to a (non-existent) static class member. If that existed, it would exist as a single shared instance for the entire class, and you would in fact initialize it as you did.
But you have an instance variable, which means that every instance of the class has its own copy. To initialize that, you'd do what sth say; initialize it in the class's ctor, either in the ctor body or better, as sth suggests, in the initializer list.