类与对象
Animal.h 文件
Animal_Impl.cpp文件:
Dog.h 类的头文件
Dog_Impl.cpp 文件
TestMain.cpp 测试文件
Animal.h 文件
#include<iostream.h>
class Animal{
// 定义属性
protected:
int age;
int weight;
//定义方法
public:
Animal();
~Animal();
void setAge(int sage);
int getAge();
void setWeight(int sweight);
int getWeight();
void eat();
void sleep();
}; //记住加 ; 号
Animal_Impl.cpp文件:
#include"Animal.h" 包含自定义的头文件
using namespace std;
Animal::Animal(){
}
Animal::~Animal(){}
void Animal::setAge(int sage){
age = sage;
}
int Animal::getAge(){
return age;
}
void Animal::setWeight(int sweight){
weight = sweight;
}
int Animal::getWeight(){
return weight;
}
void Animal::eat(){
cout<<"Animal eatting......"<<endl;
}
void Animal::sleep(){
cout<<"Animal is sleepping......"<<endl;
}
Dog.h 类的头文件
#include<iostream.h>
#include"Animal.h" 包含父类的头文件
class Dog : public Animal{ //Animal必须有实现 才可以继承
protected: 定义自己的属性
int color;
public:
Dog();
~Dog();
void setColor(int c);
int getColor();
void speak();
};
Dog_Impl.cpp 文件
#include"Dog.h" 包含头文件
using namespace std;
Dog::Dog(){}
Dog::~Dog(){}
void Dog::setColor(int c){
color = c;
}
int Dog::getColor(){
return color;
}
void Dog::speak(){
cout<<"dog speak wang wang wang"<<endl;
}
TestMain.cpp 测试文件
#include"Dog.h"
using namespace std;
int main(){
Dog dog;
dog.setAge(3); // 继承父类中的方法
cout<<"the dog's age is: "<<dog.getAge()<<endl;
dog.setWeight(2);// 继承父类中的方法
cout<<"the dog's Weight is: "<<dog.getWeight()<<endl;
dog.setColor(1);//dog类中的方法
cout<<"the dog's color is: "<<dog.getColor()<<endl;
dog.speak();
// dog.age = 1;
// cout<<"the dog's age is: "<<dog.age<<endl;
return 0;
}
/**
* the dog's age is: 3
the dog's Weight is: 2
the dog's color is: 1
dog speak wang wang wang
*
* */