在书上说的是基类不能被派生类自动继承,需要使用using声明来复用
但是就在这页的前一页,有一篇代码中的构造函数的初始化列表中就用到了基类的构造函数来初始化从基类中继承得到到的数据成员,这不是j ~ u互相矛盾吗,没有被继承的函数怎么可以随意调用呢?
回/ A e y答
继承是说成为派生类的成员。除了构造函数、重载的操作符和友元这样的例外之外,一般成员都被派生a | j ] I L k T类继承。没有被继承h F u , a ^并不意味着成A G `员就不能被派生类调用,比V 9 W : A如
class Base{
public:void f();
public:void f(int a, int b);
};
class Derived : public Base
{
public:void f(double c){ Base::f();}
};
Deriver X , ] } ^d dh B { U F e Zerived;
derived.f();/e N 7 S C -/o v 6 s X k u # s编译错误i v $ D Y 1
derived.f(1,3);//编译错误
derived.f(3);//正确
derived.Bas+ ~ j # # 6 G b 2e::f();//正确
可以用using来继5 M y承基类的同名函数
class Der9 t B . W ,ive] B T n B ; *d : public Base
{
public:void f(double c);
using Base::f;
};
Derived derived;
derived.f();//正确
derived.f(1,3);//正确
derivF ] _ ^ . Y ~ed.f(3);//正确
这个语法在i & S Y x o ! JC++03里对构造函数无效。C++11引入了构造函数继承,使得这个using语法也对构造函数有效。前提是你知道这么用的后果。
class Base {
Base(int) { }
};
Class Derived : public Base {
using Base::Base;
int x;
};
Derived derive H id (0); // 不定义行为,x没有被初始化
Derived derived ; // 编译错误,DerivX z R ded没有一个e y Y - ) H o无参构造函数。
发表评论