派生类的构造函数和复制控制成员不能继承,每个类定义自己的构造函数和复制控制成员,像任何类一样,如果类没有定义自己的构造函数和复制控制成员,编译器自动合成。
1.构造函数
派生类的构造函数先要初始化基类的成员,然后初始化本类的成员
下面定义一个Father类,头文件如下:
#if !defined(AFX_FATHER_H__C5B84CD6_0B79_4806_BEDA_035EB4183F8B__INCLUDED_)
#define AFX_FATHER_H__C5B84CD6_0B79_4806_BEDA_035EB4183F8B__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <string>
class Father
{
public:
Father();
Father(std::string job,std::string address);
virtual ~Father();
virtual void sayHello();
std::string job;
std::string address;
};
#endif // !defined(AFX_FATHER_H__C5B84CD6_0B79_4806_BEDA_035EB4183F8B__INCLUDED_)
源文件如下:
#include "Father.h"
#include<iostream>
Father::Father()
{
}
Father::Father(std::string job,std::string address)
{
this->job=job;
this->address=address;
}
Father::~Father()
{
}
void Father::sayHello()
{
std::cout<<"Hello"<<std::endl;
}
下面写一个Son类使用public继承Father,那么,Son类的构造函数可以如下写
Son::Son(std::string job,std::string address,std::string pcname,std::string phonename):Father(job,address)
{
this->pcname=pcname;
this->phonename=phonename;
}
首先调用基类的构造函数,初始化基类的成员。
2.复制构造函数
Son::Son(const Son& ss):Father(ss)
{
this->pcname=ss.pcname;
this->phonename=ss.phonename;
}
先调用基类的复制构造函数,初始化基类的成员,然后初始化本类的成员
3.赋值操作符
Son& Son::operator =(Son& ss)
{
Father::operator=(ss);
this->pcname=ss.pcname;
this->phonename=ss.phonename;
return *this;
}
显式调用基类的赋值操作符。