构造方法用来初始化类的对象,与父类的其它成员不同,它不能被子类继承(子类可以继承父类所有的成员变量和成员方法,但不继承父类的构造方法)。因此,在创建子类对象时,为了初始化从父类继承来的数据成员,系统需要调用其父类的构造方法。
2.如果没有显式的构造函数,编译器会给一个默认的构造函数,并且该默认的构造函数仅仅在没有显式地声明构造函数情况下创建。
3.如果子类调用父类带参数的构造方法,需要用初始化父类成员对象的方式.
办法1:
#include <iostream.h>
class animal
{
public:
animal(int height, int weight) //有且仅有 有参参数,必须显性调用
{
cout<<"animal construct"<<endl;
}
…
};
class fish:public animal
{
public:
fish():animal(400,300)
{
cout<<"fish construct"<<endl;
}
…
};
void main()
{
fish fh;
}
在fish类的构造函数后,加一个冒号(:),然后加上父类的带参数的构造函数。这样,在子类的构造函数被调用时,系统就会去调用父类的带参数的构造函数去构造对象。
办法二:
使用using来继承基类构造函数 。具体参考:c++11中using的使用_baidu_16370559的博客-CSDN博客
#include <iostream>
using namespace std;
class Base
{
public:
Base(int a, int b, int c) //有且仅有 有参参数,必须显性调用
{
m_a = a;
m_b = b;
m_c = c;
cout << "父类的构造函数m_a :" << m_a << endl;
}
public:
int m_a;
int m_b;
int m_c;
};
class Child : public Base
{
public:
//子类继承父类构造方法
using Base::Base;
};
int main()
{
//子类继承父类构造方法创建对象
Child ch1(1, 2, 3);
return 0;
};
更进一步
#include <iostream>
using namespace std;
class Base
{
public:
Base(int a, int b, int c)
{
m_a = a;
m_b = b;
m_c = c;
cout << "父类的构造函数m_a :" << m_a << endl;
}
public:
int m_a;
int m_b;
int m_c;
};
class Child : public Base
{
public:
//子类继承父类构造方法
using Base::Base;
//子类委托父类构造方法
Child(int a, int b, int c, double d) : Base(a, b, c)
{
m_d = d;
cout << "子类的构造函数m_d :" << m_d << endl;
}
double m_d;
};
int main()
{
//子类继承父类构造方法创建对象
Child ch1(1, 2, 3);
cout << "----------------------------" << endl;
//子类委托父类构造方法创建对象
Child ch(4, 5, 6, 7.7);
return 0;
};