为什么不能如下设置接口类的成员变量
所以我有一个接口类
class interfaceClass
{
public:
virtual void func1( void ) = 0;
virtual void func2( void ) = 0;
protected:
int m_interfaceVar;
}
和一个继承它的类。 为什么我不能如下设置接口类的成员变量。
class inhertitedClass : public interfaceClass
{
inheritedClass(int getInt): m_interfaceVar(getInt){};
~inheritedClass(){};
}
我必须这样做,
class inhertitedClass : public interfaceClass
{
inheritedClass(int getInt){ m_interfaceVar = getInt;}
~inheritedClass(){};
}
如果这是一个愚蠢的问题,我很抱歉,但有一天晚上我刚刚遇到它,当时我正在将抽象类切换为接口类(回到抽象类)。
So i have a interface class
class interfaceClass
{
public:
virtual void func1( void ) = 0;
virtual void func2( void ) = 0;
protected:
int m_interfaceVar;
}
and a class that inherits from it.
Why can't i set the member variable of the interface class as follows.
class inhertitedClass : public interfaceClass
{
inheritedClass(int getInt): m_interfaceVar(getInt){};
~inheritedClass(){};
}
and i have to do it like this
class inhertitedClass : public interfaceClass
{
inheritedClass(int getInt){ m_interfaceVar = getInt;}
~inheritedClass(){};
}
I'm sorry if this is a dumb question, but i just ran in to it the other night while i was switching my abstract class into an interface class (the back to an abstract class).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
构造函数中的初始值设定项列表可以首先指定基类的构造函数。通过剥夺
interfaceClass
的(受保护的)构造函数(显然应该),你就切断了这条生命线。因此,添加受保护的构造函数,例如:
然后然后您可以以正确的方式做事,即
The initializer list in a constructor can specify the ctor for the base classes first and foremost. By depriving
interfaceClass
of a (protected) constructor (which it obviously should have) you've cut off that lifeline.So add that protected ctor, e.g.:
and then you can do things the right way, namely
当
inheritedClass
到达其初始化列表时,m_interfaceVar
已经被初始化。您无法对其进行第二次初始化。您的选择是向
interfaceClass
提供一个初始化m_interfaceVar
的构造函数,或者只是将其分配到inheritedClass
构造函数的主体中:或者
By the time
inheritedClass
gets to it's initializer list,m_interfaceVar
has already been initialized. You can't initialize it a second time.Your options are to provide a constructor to
interfaceClass
that initializesm_interfaceVar
, or just assign it in the body ofinheritedClass
s constructor:or
试试这样:
...事实上,如果您不为
interfaceClass
创建受保护或私有构造函数,编译器会默默地为您和用户创建一个将能够创建接口的实例(您确实希望它是一个抽象基类,对吧?)Try it like this:
...in fact, if you don't create a protected or private constructor for
interfaceClass
, the compiler will silently create one for you, and users will be able to create instances of your interface (you did want it to be an abstract base class, right?)