C++学习(一)第一个程序

跑通的第一个程序

//#ifndef ANIMAL_H
//#define ANIMAL_H  //预定义,防止头文件类冲突,一般在类的头文件中使用

#include<iostream>
using namespace std;

class Animal
{
public:
	Animal()
	{
		cout << "animal construct" << endl;
	}
	~Animal()
	{
		cout << "animal deconstruct" << endl;
	}
	void eat()
	{
		cout << "animal eat" << endl;
	}
	void sleep()
	{
		cout << "animal sleep" << endl;
	}
	virtual void breathe()//virtual将函数变为虚函数,做迟邦定,派生类内存在前,否则,基类内存在前
	{
		cout << "animal breathe" << endl;
	}
	//virtual void breathe()=0;是纯虚函数,纯虚函数的类是抽象类,不能实例化,只能被继承,没有过程,不具体实现,只能由派生类自己定义
};

class Fish : public Animal//类继承
{
public:
	Fish() : Animal(), a(1)//构造函数调用父类,构造时可对常量进行构造,因为常量在初始化后必须被赋值
	{
		cout << "fish construct" << endl;
	}
	~Fish()
	{
		cout << "fish deconstruct" << endl;
	}
	void breathe()//函数重写
	{
		Animal::breathe();//作用域标识符,用于表示函数属于那一个类
		cout << "fish breathe" << endl;
	}
private:
	const int a;
};

void fn(Animal* pt)
{
	pt->breathe();
}

int main()
{
	Fish fh;
	Animal* pt;//定义Animal的指针
	pt = &fh;//将fh地址赋给指针
	fn(pt);//调用Aniaml的breathe()
	int a = 6;
	int& b = a;//设置一个a的引用b,就是给a起个别名,一般用于函数传参
}

//#endif
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值