//Animal.h//
#ifndef ANIMAL_H_H
#define ANIMAL_H_H
class Animal
{
public:
Animal(int height,int weight);
void eat();
void sleep();
virtual void breathe();//=0;
};
#endif
//Fish.h//
#include "Animal.h"
#ifndef FISH_H_H
#define FISH_H_H
class Fish : public Animal
{
public:
Fish();
void breathe();
};
#endif
//main.cpp//
#include <iostream.h>
#include "Animal.h"
#include "Fish.h"
void fn(Animal *pAn)
{
pAn->breathe();
}
void main()
{
//Animal an;
//an.eat();
// an.breathe();
Fish fh;
Animal *pAn;
pAn=&fh;
fn(pAn);
}
//Animal.cpp//
#include "Animal.h"
#include <iostream.h>
Animal::Animal(int height,int weight)
{
}
void Animal::eat()
{
cout<<"animal eat"<<endl;
}
void Animal::sleep()
{
cout<<"animal sleep"<<endl;
}
void Animal::breathe()
{
cout<<"aniaml breathe"<<endl;
}
//Fish.cpp//
#include "Fish.h"
#include <iostream.h>
Fish::Fish():Animal(300,400)
{
}
void Fish::breathe()
{
cout<<"fish bubble"<<endl;
}
(1)在C语言中结构体不能包含成员函数,而C++可以;
(2)构造函数没有返回值,每个类都必须有构造函数和析构函数,如果没有写,系统自动补上;
(3)函数重载(条件:函数参数的个数(要赋值的),类型不同),函数重载与函数覆盖的区别:函数重载是发生在同一个类中,而函数覆盖是发生在父类和子类中;
下面函数不能构成重载:
第一种情况:(1)void output();
(2)int output();
第二种情况:(1)void output(int a,int b=5);
(2)void output(int a);
(4)多态性(条件:基类类中的成员函数为虚函数,并且要传递子类地址);virtual
(5)避免重复定义类:
例如:
#ifndef ANIMAL_H_H_H
#define ANIMAL_H_H_H
class animal
{
}
#endif
#ifndef FISH_H_H_H
#define FISH_H_H_H
class fish:public animal
{
}
#endi
(6)程序编译连接运行过程:预处理(把头文件加入)->在内存中把各个源文件单独翻译成翻译单元->各个源文件单独编译(生成obj文件)—>把obj文件,头文件,标准库函数连接-》运行。
只编译源文件,不对头文件编译。
(7)this指针:每一个类对象都会有分配一个this指针指向这个类
例如:
void output(int x,int y)
{
this->x=x;//区分出形参和类变量;
this->y=y;
}
(8)private,projected,public继承方式:
private继承能继承基类中的public和projected类,并且继承后都成private类;
projected在基类中的作用相当与private,不能直接由外部使用变量或成员函数,但他有跟private不一样就他可以被继承,他被public和projected继承后变成projected类型;
public继承可以继承基类是public和projected的类,继承后的类保存基类状态(当然除继承基类中的private(不能被继承哈)).
(9)引用
int a=5;
int &b=a;//b是a的引用,改变b就是改变a;
cout<<b; 5
b=7;
cout<<a<<b;7.7
调用函数:void change(&x,&y)
{
}
main()
{
change(x,y);交换x,y值;可读性强
}
优等同:
void change(int *PA,int *PB)
{
int temp;
temp=*PA;
...
};
main()
{
change(&x,&y);
}