实验演示: 组合关系的描述
#include <iostream>
#include <string>
using namespace std;
class Memory
{
public:
Memory()
{
cout << "Memory()" << endl;
}
~Memory()
{
cout << "~Memory()" << endl;
}
};
class Disk
{
public:
Disk()
{
cout << "Disk()" << endl;
}
~Disk()
{
cout << "~Disk()" << endl;
}
};
class CPU
{
public:
CPU()
{
cout << "CPU()" << endl;
}
~CPU()
{
cout << "~CPU()" << endl;
}
};
class MainBoard
{
public:
MainBoard()
{
cout << "MainBoard()" << endl;
}
~MainBoard()
{
cout << "~MainBoard()" << endl;
}
};
class Computer
{
Memory mMem;
Disk mDisk;
CPU mCPU;
MainBoard mMainBoard;
public:
Computer()
{
cout << "Computer()" << endl;
}
void power()
{
cout << "power()" << endl;
}
void reset()
{
cout << "reset()" << endl;
}
~Computer()
{
cout << "~Computer()" << endl;
}
};
int main()
{
Computer c;
return 0;
}
类之间的组合关系的特点: (1)将其它类的对象作为当前类的成员使用 (2)当前类的对象与成员对象的声明期相同 (3)成员对象在其他用法上与普通对象完全一致
继承关系:父子关系 (父类(基类)) (子类(派生类)
面向对象中的继承指类之间的父子关系: (1)子类拥有父亲的所有属性和行为 (2)子类是一种特殊的父类 (3)子类对象可以当做父类对象使用 (4)子类中可以添加父亲没有的方法和属性
C++中通过下面的方式描述继承关系:
class Parent
{
int mv;
public:
void method()
{
}
};
class Child : public Parent
{
};
实验演示:继承体验
#include <iostream>
#include <string>
using namespace std;
class Parent
{
int mv;
public:
Parent()
{
cout << "Parent()" << endl;
mv = 100;
}
void method()
{
cout << "mv = " << mv << endl;
}
};
class Child : public Parent
{
public:
void hello()
{
cout << "Hello" << endl;
}
};
int main()
{
Child c;
Parent p1 = c;
c.method();
c.hello();
return 0;
}
重要规则: (1)子类是一个特殊的父类 (2)子类对象可以直接初始化父类对象 (3)子类对象可以直接赋值给父类对象 (4)子类对象可以当做父类对象使用
继承的意义:继承是C++中代码复用的重要手段。通过继承,可以获得父类的所有功能,并且可以在子类中重写已有功能,或者添加新功能
编程实验:继承的强化体验
#include <iostream>
#include <string>
using namespace std;
class Memory
{
public:
Memory()
{
cout << "Memory()" << endl;
}
~Memory()
{
cout << "~Memory()" << endl;
}
};
class Disk
{
public:
Disk()
{
cout << "Disk()" << endl;
}
~Disk()
{
cout << "~Disk()" << endl;
}
};
class CPU
{
public:
CPU()
{
cout << "CPU()" << endl;
}
~CPU()
{
cout << "~CPU()" << endl;
}
};
class MainBoard
{
public:
MainBoard()
{
cout << "MainBoard()" << endl;
}
~MainBoard()
{
cout << "~MainBoard()" << endl;
}
};
class Computer
{
Memory mMem;
Disk mDisk;
CPU mCPU;
MainBoard mMainBoard;
public:
Computer()
{
cout << "Computer()" << endl;
}
void power()
{
cout << "power()" << endl;
}
void reset()
{
cout << "reset()" << endl;
}
~Computer()
{
cout << "~Computer()" << endl;
}
};
class HPBook : public Computer
{
string os;
public:
HPBook()
{
os = "Windows 8";
}
void install(string os)
{
os = os;
}
void OS()
{
cout << os << endl;
}
};
class MacBook : public Computer
{
public:
void OS()
{
cout << "Mac os" << endl;
}
};
int main()
{
Computer c;
cout << endl;
HPBook hp;
hp.power();
hp.install("Ubuntu 16.04");
hp.OS();
cout << endl;
MacBook mac;
mac.OS();
return 0;
}
|