跑通的第一个程序
//#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