将参数传递给基类构造函数C++; < >我喜欢将类声明和定义保持在C++中。因此,在标题中,我可以定义一个“基类”,如下所示: # Base.h class Base { int n; public: Base(int x); }; #Derived.h class Derived : public Base { int t; public: Derived(int y) : Base(t) {t = y;} }
并在cpp文件中定义其构造函数实现,即将参数传递给基类构造函数C++; < >我喜欢将类声明和定义保持在C++中。因此,在标题中,我可以定义一个“基类”,如下所示: # Base.h class Base { int n; public: Base(int x); }; #Derived.h class Derived : public Base { int t; public: Derived(int y) : Base(t) {t = y;} },c++,class,inheritance,constructor,C++,Class,Inheritance,Constructor,并在cpp文件中定义其构造函数实现,即 # Base.c Base::Base(int x) { n = x; } 现在,如果我定义一个继承“基类”的“派生”类,我可以按如下方式向基类传递参数: # Base.h class Base { int n; public: Base(int x); }; #Derived.h class Derived : public Base { int t; public: Derived(int y)
# Base.c
Base::Base(int x)
{
n = x;
}
现在,如果我定义一个继承“基类”的“派生”类,我可以按如下方式向基类传递参数:
# Base.h
class Base
{
int n;
public:
Base(int x);
};
#Derived.h
class Derived : public Base
{
int t;
public:
Derived(int y) : Base(t) {t = y;}
}
但这样做需要将派生类的构造函数体放在头文件中,即
{t=y;}
,因此构造函数定义不再与其声明分离。是否有一种方法可以将参数传递给类的基类构造函数,使我仍然能够在cpp文件中定义派生类的构造函数?是的,头文件中有:
class Derived : public Base
{
int t;
public:
Derived(int y); // Declaration of constructor
};
在cpp文件中时:
Derived::Derived(int y) : Base(t) { // Definition of constructor
t = y;
}
类构造函数的定义以及内联类定义中都允许使用。如果您感兴趣,我还建议您考虑两个关于初始化顺序的小注意事项,以及在执行复合构造函数体之前初始化成员的事实
有没有一种方法可以将参数传递给类的基类构造函数,使我能够在cpp文件中为派生类定义构造函数
当然有。标头可以声明构造函数,就像您对Base
所做的那样:
class Derived : public Base
{
int t;
public:
Derived(int y);
};
Derived::Derived(int y) : Base(y), t(y) {}
然后,您可以在源文件中实现它,就像您对Base
所做的那样:
class Derived : public Base
{
int t;
public:
Derived(int y);
};
Derived::Derived(int y) : Base(y), t(y) {}
注意,必须将参数y
,而不是(尚未初始化)成员t
传递给基构造函数。基本子对象总是在成员之前初始化