#pragma once
class Animal
{
public:
Animal();
~Animal();
void SetWeight(int nWeight); //设置重量
int GetWeight(); //获得重量
private:
int m_nWeight;
};
#include "stdafx.h"
#include "Animal.h"
#include <string>
#include <iostream>
using namespace std;
Animal::Animal()
{
cout << "Animal 类的构造函数被调用!" << endl;
}
Animal::~Animal()
{
cout << "Animal 类的析构函数被调用!" << endl;
}
void Animal::SetWeight(int nWeight) //设置重量
{
m_nWeight=nWeight;
}
int Animal::GetWeight() //获得重量
{
return m_nWeight;
}
#pragma once
#include "Animal.h"
#include <iostream>
using namespace std;
class Horse : virtual public Animal //继承自Animal类,Animal类是虚基类
{
public:
Horse();
~Horse();
void run(); //奔跑
};
#include "stdafx.h"
#include "Horse.h"
Horse::Horse()
{
cout << "Horse 类的构造函数被调用!" << endl;
}
Horse::~Horse()
{
cout << "Horse 类的析构函数被调用!" << endl;
}
void Horse::run() //奔跑
{
cout << "I can run!" << endl;
}
#pragma once
#include "Animal.h"
#include <iostream>
using namespace std;
class Bird : virtual public Animal //继承自Animal类,Animal类是虚基类
{
public:
Bird();
~Bird();
void fly(); //奔跑
};
#include "stdafx.h"
#include "Bird.h"
Bird::Bird()
{
cout << "Bird 类的构造函数被调用!" << endl;
}
Bird::~Bird()
{
cout << "Bird 类的析构函数被调用!" << endl;
}
void Bird::fly() //奔跑
{
cout << "I can fly!" << endl;
}
#pragma once
#include "Horse.h"
#include "Bird.h"
class Pegasus : public Horse, public Bird //多重继承
{
public:
Pegasus();
~Pegasus();
};
#include "stdafx.h"
#include "Pegasus.h"
Pegasus::Pegasus()
{
cout << "Pegasus 类的构造函数被调用!" << endl;
}
Pegasus::~Pegasus()
{
cout << "Pegasus 类的析构函数被调用!" << endl;
}
// HorseExample.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include"Pegasus.h"
int _tmain(int argc, _TCHAR* argv[])
{
Pegasus p; //定义一个对象
p.run();
p.fly();
p.SetWeight(5); //设置重量
cout << p.GetWeight() << endl;
getchar();
return 0;
}
运行结果: