类的继承

类与对象
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
*
* */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值