[英]Why I need to set a variable to some value in base class when I declare a derived class?
I dont understand why, when i try to create a object of a base class, i can, but only without declaring derived class, and when declare Derived i need to set argument value to "= 0" in base class constructor? 我不明白为什么,当我尝试创建基类的对象时,我可以但只能在不声明派生类的情况下进行操作,而当声明派生类时,我需要在基类构造函数中将参数值设置为“ = 0”?
#include <cstdlib>
using namespace std;
class Base {
public:
int m_nValue;
Base(int nValue=0) //<--- why here i need = 0 ?
: m_nValue(nValue)
{}
};
class Derived: public Base {
public:
double m_dValue;
Derived(double dValue)
: m_dValue(dValue)
{}
};
int main(int argc, char** argv) {
Base cBase(5); // use Base(int) constructor
return 0;
}
No you don't. 不,你不会。 The problem is that when you subclass, you never give any value to the base class ctor, something like this: 问题是,当您子类化时,您永远不会给基类ctor赋予任何值,如下所示:
Derived(double dValue) : Base(0), m_dValue(dValue) {}
So the compiler looks at the base class and search either: a ctor with no argument, or a ctor with default values (he doesn't look at the default ctor as defining a ctor removes the default ctor). 因此,编译器查看基类并搜索:不带参数的ctor或具有默认值的ctor(他不查看默认ctor,因为定义ctor会删除默认ctor)。 Either: 要么:
class Base {
public:
int m_nValue;
Base() : m_nValue(0) {}
Base(int nValue) : m_nValue(nValue) {}
};
or 要么
class Base {
public:
int m_nValue;
Base(int nValue=0) : m_nValue(nValue) {}
};
Base(int nValue = 0)
will also act as the default constructor, since a default value for nValue
has been supplied. Base(int nValue = 0)
也将充当默认构造函数,因为已经提供了nValue
的默认值。 Currently, your Derived
constructor will call this constructor implicitly, with nValue
set to 0. 当前,您的Derived
构造函数将隐式调用此构造函数,并将nValue
设置为0。
Formally you don't actually need to do that - but that would mean that the user of your class would have to supply an explicit value for nValue
and you would have to write a default constructor . 形式上您实际上并不需要这样做-但这意味着您的类的用户必须为nValue
提供一个显式的值,并且您必须编写一个默认的构造函数 。 You could achieve the latter by writing Base() = default;
您可以通过编写Base() = default;
来实现后者Base() = default;
although then the member m_nValue
will not be initialised unless you use the C++11 curly brace notation (eg Base b{};
). 但是, 除非您使用C ++ 11大括号表示法(例如Base b{};
), 否则不会初始化成员m_nValue
。 (Note that the behaviour on reading an uninitialised variable is undefined .) (请注意,读取未初始化变量的行为是undefined 。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.