小甲鱼-C++ 16 this指针、类的继承

1、通过一个典型的例子来认识它(this指针)

class Human
{
    char fishc;
    Human(char fishc);
}
 
Human::Human(char fishc)
{
    fishc = fishc;
}

Human()构造器有一个名为fishc的参数,虽然它与Human类里面的属性同名,但却是不相干的两样东西,所以并没有错.

可是,问题是怎样让构造器知道哪个是参数,哪个是属性呢?

这时候就需要用到this指针 : this-> fishc = fishc

通过上述语句,编译器就知道赋值操作符左边将被解释为当前对象的fishc属性,右边将被解释为构造器传入来的fishc参数

注意:

使用this指针的基本原则是:如果代码不存在二义性隐患,就不必使用this指针

2、类的继承

通过继承机制,程序员可以对现有的代码进行进一步的扩展,并应用在新的程序中。

(1)基类和子类

基类:可以派生出其他的类,也可以成为父类或超类

子类:从基类中派生出来的类

class SubClass:public SuperClass{...}
class Pig:public Animal{...}
#include <iostream>
#include <string>
 
using namespace std;
 
class Animal
{
public:
	string mouth;
 
	void eat();
	void sleep();
	void drool();
	
};
 
class Pig:public Animal
{
public:
	void climb();
 
};
 
class Turtle:public Animal
{
public:
	void swim();
};
 
void Animal::eat()
{
	cout << "I am eating!" << endl;
}
 
void Animal::sleep()
{
	cout << "I am sleeping! Dont disturb me" <<endl;
}
 
void Animal::drool()
{
	cout << "我是公的....";
}
 
void Pig::climb()
{
	cout << "正在爬树..." << endl;
}
 
void Turtle::swim()
{
	cout << "正在游泳..." << endl;
}
 
int main()
{
	Pig pig;
	Turtle turtle;
 
	pig.eat();
	turtle.eat();
	pig.climb();
	turtle.swim();
 
	return 0;
}

运行结果

I am eating!
I am eating!
正在爬树...
正在游泳...

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值