fun.h
- #ifndef __FUN_H__
- #define __FUN_H__
-
- #include
-
- using namespace std;
-
- // 定义一个Sofa类
- class Sofa
- {
- private:
- string sitting;
-
- public:
- Sofa(); // 无参构造函数
- Sofa(string s); // 有参构造函数
- ~Sofa(); // 析构函数
- Sofa(const Sofa &s); // 拷贝构造函数
- Sofa &operator=(const Sofa &s); // 拷贝赋值函数
- };
-
- // 定义一个Bed类
- class Bed
- {
- private:
- string sleeping;
-
- public:
- Bed(); // 无参构造函数
- Bed(string s); // 有参构造函数
- ~Bed(); // 析构函数
- Bed(const Bed &b); // 拷贝构造函数
- Bed &operator=(const Bed &b); // 拷贝赋值函数
- };
-
- // 定义一个Sofa_Bed类
- class Sofa_Bed : public Sofa, public Bed
- {
- private:
- string color;
-
- public:
- Sofa_Bed(); // 无参构造函数
- Sofa_Bed(string s, string ss, string c); // 有参构造函数
- ~Sofa_Bed(); // 析构函数
- Sofa_Bed(const Sofa_Bed &ss); // 拷贝构造函数
- Sofa_Bed &operator=(const Sofa_Bed &ss); // 拷贝赋值函数
- };
-
- #endif
main.cpp
- // 多继承实现沙发床
- #include "03_fun.h"
-
- int main()
- {
- Sofa_Bed s1; // 自动调用无参构造函数
-
- cout << "--------------------" << endl;
- Sofa_Bed s2("可坐", "可躺", "红色"); // 自动调用有参构造函数
-
- cout << "--------------------" << endl;
- Sofa_Bed s3(s2); // 自动调用拷贝构造函数
-
- cout << "--------------------" << endl;
- s1 = s2; // 自动调用拷贝赋值函数
-
- cout << "--------------------" << endl;
- return 0;
- // 自动调用析构函数
- }
fun.cpp
- #include "03_fun.h"
-
-
- // Sofa::无参构造函数
- Sofa::Sofa()
- {
- cout << "Sofa::无参构造函数" << endl;
- }
- // Sofa::有参构造函数
- Sofa::Sofa(string s) : sitting(s)
- {
- cout << "Sofa::有参构造函数" << endl;
- }
- // Sofa::析构函数
- Sofa::~Sofa()
- {
- cout << "Sofa::析构函数" << endl;
- }
- // Sofa::拷贝构造函数
- Sofa::Sofa(const Sofa &s) : sitting(s.sitting)
- {
- cout << "Sofa::拷贝构造函数" << endl;
- }
- // Sofa::拷贝赋值函数
- Sofa &Sofa::operator=(const Sofa &s)
- {
- cout << "Sofa::拷贝赋值函数" << endl;
- sitting = s.sitting;
- return *this;
- }
-
- // Bed::无参构造函数
- Bed::Bed()
- {
- cout << "Bed::无参构造函数" << endl;
- }
- // Bed::有参构造函数
- Bed::Bed(string s) : sleeping(s)
- {
- cout << "Bed::有参构造函数" << endl;
- }
- // Bed::析构函数
- Bed::~Bed()
- {
- cout << "Bed::析构函数" << endl;
- }
- // Bed::拷贝构造函数
- Bed::Bed(const Bed &b) : sleeping(b.sleeping)
- {
- cout << "Bed::拷贝构造函数" << endl;
- }
- // Bed::拷贝赋值函数
- Bed &Bed::operator=(const Bed &b)
- {
- cout << "Bed::拷贝赋值函数" << endl;
- sleeping = b.sleeping;
- return *this;
- }
-
- // Sofa_Bed::无参构造函数
- Sofa_Bed::Sofa_Bed()
- {
- cout << "Sofa_Bed::无参构造函数" << endl;
- }
- // Sofa_Bed::有参构造函数
- Sofa_Bed::Sofa_Bed(string s, string ss, string c) : Sofa(s), Bed(ss), color(c)
- {
- cout << "Sofa_Bed::有参构造函数" << endl;
- }
- // Sofa_Bed::析构函数
- Sofa_Bed::~Sofa_Bed()
- {
- cout << "Sofa_Bed::析构函数" << endl;
- }
- // Sofa_Bed::拷贝构造函数
- Sofa_Bed::Sofa_Bed(const Sofa_Bed &ss) : Sofa(ss), Bed(ss), color(ss.color)
- {
- cout << "Sofa_Bed::拷贝构造函数" << endl;
- }
- // Sofa_Bed::拷贝赋值函数
- Sofa_Bed &Sofa_Bed::operator=(const Sofa_Bed &ss)
- {
- cout << "Sofa_Bed::拷贝赋值函数" << endl;
- Sofa::operator=(ss);
- Bed::operator=(ss);
- color = ss.color;
- return *this;
- }
