C++的派生类中,可以使用基类命名空间,调用基类的成员函数和成员变量,如下所示。
class Base {
public:
int a = 5;
void func() {
cout << " 输出基类a:" << endl;
cout << " " << a << endl;
};
};
class Derived : public Base {
public:
int a = 4;
void func() {
cout << " 输出派生类a:" << endl;
cout << " " << a << endl;
cout << " 输出基类a:" << endl;
cout << " " << Base::a << endl;
};
void call() {
cout << "调用派生类func方法" << endl;
func();
cout << "调用基类func方法" << endl;
Base::func();
}
};
int main()
{
Derived d;
d.call();
return 0;
}
假设这样一个情况,我们在派生类的构造函数中,希望调用基类的构造函数,但基类没有和派生类构造函数参数相匹配的构造函数。例如下面:
class Base {
public:
Base(int i) { // 基类没有默认构造函数,当前构造函数仅接受一个参数
cout << "调用基类构造函数" << endl;
};
};
class Derived : public Base {
public:
Derived(int i, int j) { // 派生类构造函数接受两个参数,语法错误,no default constructor exists for class Base
cout << "调用派生类构造函数" << endl;
};
};
默认情况下,派生类会调用基类相同参数的构造函数,但这里没有相同参数的构造函数,便会有语法错误,即时我们在派生类的构造函数里调用Base::Base()
也不行。解决方法是,在派生类构造函数的初始化列表里调用基类的构造函数,如下:
class Base {
public:
Base(int i) { // 基类没有默认构造函数,当前构造函数仅接受一个参数
cout << "调用基类构造函数" << endl;
};
};
class Derived : public Base {
public:
Derived(int i, int j): Base(i) { // 派生类构造函数接受两个参数,语法错误,no default constructor exists for class Base
cout << "调用派生类构造函数" << endl;
};
};
int main()
{
Derived d(1, 2);
return 0;
}
网友评论