类
构造函数
析构函数
成员变量
成员函数
类的定义
#ifndef HUMAN_HUMAN_H
#define HUMAN_HUMAN_H
#include <iostream>
namespace avdance{
class Human{
public:
Human(){
std::cout <<"construct human..." << std::endl;
age = 0;
sex = 0;
};
~Human(){
std::cout <<"destruct human..."<< std::endl;
}
public:
void setAge(int age);
int getAge();
void setSex(int sex);
int getSex();
private:
int age; //
int sex; //0:male 1:female
};
}//namespace avdance
#endif //HUMAN_HUMAN_H
#include "Human.h"
namespace avdance{
void Human::setAge(int a){
age = a;
}
int Human::getAge(){
return age;
}
void Human::setSex(int s){
sex = s;
}
int Human::getSex(){
return sex;
}
}//namespace avdance
类的使用
#include <iostream>
#include "Human.h"
using namespace avdance;
int main(int argc,char* argv[])
{
//Human human;
Human* human = new Human();
human->setAge(20);
human->setSex(1);
std::cout << "human:" << human->getAge() << "," << human->getSex() << std::endl;
}
类的继承
#ifndef AIRPLANE_AIRPLANE_H
#define AIRPLANE_AIRPLANE_H
#include <iostream>
namespace avdance{
class AirPlane{
public:
AirPlane(){
wings = 2;
wheels = 3;
engines = 1;
}
~AirPlane(){ }
public:
void setWings(int w);
int getWings();
void setWheels(int w);
int getWheels();
void setEngines(int e);
int getEngines();
public:
void fly();
private:
int wings;
int wheels;
int engines;
};
}//namespace avdance
#endif //AIRPLANE_AIRPLANE_H
#include <iostream>
#include "AirPlane.h"
namespace avdance{
void AirPlane::setWings(int w) {
wings = w;
}
int AirPlane::getWings(){
return wings;
}
void AirPlane::setWheels(int w) {
wheels = w;
}
int AirPlane::getWheels() {
return wheels;
}
void AirPlane::setEngines(int e) {
engines = e;
}
int AirPlane::getEngines() {
return engines;
}
void AirPlane::fly() {
std::cout << "fly..." << std::endl;
}
}
#ifndef AIRPLANE_FIGHTERPLANE_H
#define AIRPLANE_FIGHTERPLANE_H
#include <iostream>
#include "AirPlane.h"
namespace avdance{
class FighterPlane: public AirPlane{
public:
FighterPlane(){
weapons = 1;
}
~FighterPlane(){};
public:
void setWeapons(int w);
int getWeapons();
private:
int weapons;
};
}//namespace avdance
#endif //AIRPLANE_FIGHTERPLANE_H
#include <iostream>
#include "FighterPlane.h"
namespace avdance{
void FighterPlane::setWeapons(int w){
weapons = w;
}
int FighterPlane::getWeapons() {
return weapons;
}
}//namespace avdance
#include <iostream>
#include "FighterPlane.h"
int main(int argc,char* argv[]) {
avdance::FighterPlane fp;
fp.setWings(5);
fp.setWheels(3);
fp.setWeapons(10);
std::cout << "FighterPlane:" << fp.getWings() << ","
<< fp.getWheels() << ","
<< fp.getWeapons() << "." << std::endl;
}
多态
多态指同样的方法被不同的子类执行时有不同的行为
虚函数的作用
虚析构函数的作用
纯虚函数和抽象类
接口类