C++11中提供的继承构造函数可以让派生类直接使用基类的构造函数,而无需自己再写构造函数,尤其是在基类有很多构造函数的情况下,可以极大地简化派生类构造函数的编写。
先来看没有继承构造函数之前的处理方式:
代码如下:
#include <iostream>
#include <string>
using namespace std;class Base
{
public:Base(int i):m_i(i){}Base(int i,double j):m_i(i),m_j(j){}Base(int i,double j,string k):m_i(i),m_j(j),m_k(k){}int m_i;double m_j;string m_k;
};class Child :public Base
{
public:Child(int i):Base(i){}Child(int i,double j):Base(i,j){}Child(int i,double j,string k):Base(i,j,k){}};int main()
{Child c(520, 13.14, "I Love You");cout << "int = " << c.m_i << " double = " << c.m_j << " string = " << c.m_k << endl;return 0;
}
测试结果:
继承构造函数
代码如下:
#include <iostream>
#include <string>
using namespace std;class Base
{
public:Base(int i):m_i(i){}Base(int i,double j):m_i(i),m_j(j){}Base(int i,double j,string k):m_i(i),m_j(j),m_k(k){}int m_i;double m_j;string m_k;
};class Child :public Base
{
public:using Base::Base;};int main()
{Child c(520, 13.14, "I Love You");cout << "int = " << c.m_i << " double = " << c.m_j << " string = " << c.m_k << endl;return 0;
}
测试结果:
如果子类中有跟父类一样的同名函数,就会隐藏父类的一样同名的函数。
代码如下:
#include <iostream>
#include <string>
using namespace std;class Base
{
public:Base(){}Base(int i):m_i(i){}Base(int i,double j):m_i(i),m_j(j){}Base(int i,double j,string k):m_i(i),m_j(j),m_k(k){}void func(int i){cout << "base func(int i)" << endl;}void func(int i, string str){cout << "base func(int i,string str)" << endl;}int m_i;double m_j;string m_k;
};class Child :public Base
{
public:using Base::Base;void func(){cout << "child func()" << endl;}};int main()
{Child c;c.func();//c.func(2);//error//c.func(2, "Tom");//errorreturn 0;
}
测试结果:
在子类中加入下面这条代码,则可以解除隐藏。
using Base::func;
代码如下:
#include <iostream>
#include <string>
using namespace std;class Base
{
public:Base(){}Base(int i):m_i(i){}Base(int i,double j):m_i(i),m_j(j){}Base(int i,double j,string k):m_i(i),m_j(j),m_k(k){}void func(int i){cout << "base func(int i)" << endl;}void func(int i, string str){cout << "base func(int i,string str)" << endl;}int m_i;double m_j;string m_k;
};class Child :public Base
{
public:using Base::Base;using Base::func;void func(){cout << "child func()" << endl;}};int main()
{Child c;c.func();c.func(2);c.func(2, "Tom");return 0;
}
测试结果: