小甲鱼-C++快速入门笔记(17)之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
{
	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;
}

猜你喜欢

转载自blog.csdn.net/qq_30708445/article/details/88601371