1. 关于类struct 和class,注意默认的继承级别不同(public,private)
2. 构造函数的调用顺序:
现调用父类,再调用子类的构造函数,析构函数调用顺序相反
3. 继承的类参数问题:
Class Animal
{
Public:
Anmial( int height,int weight)
{
}
};
Class fish:publicanimal
{
Public:
Fish(int height,intweight):Animal(height,weight)
{//Fishfi(300,200);
}
Fish(void):Animal(300,200) //这个最经典…..
//如在mian()中 Fish fi;
//fish 无参数但是仍然要
//满足基类的参数个数,主要还是要看初始化的时候
//是否带参初始化
{
}
};
4. 函数的重载:当函数的参数和返回值类型不同的时候才会重载,注意以下情况:
① int fn() ;void fn() ---à不能重载
② int fn(int a,int b=5); int fn(int a);--à还是不能重载…
5. 多态性:
不同于重装,该过程发生在父子类之间
在子类转化成父类类型的时候,如果要调用子类的方法,要在父类的那个特定的方法上加上virtual关键字
注意:当子类中没有该方法的时候,仍然调用父类的该方法
在类内声明,类外定义的时候,类外不带virtual关键字
6. 纯虚函数:
当父类中某个方法定义为纯虚函数的时候,如
Virtualbreath()=0;
则子类中必须实现该纯虚函数,否则不能实例化(初始化子类),当然也不能实例化父类
7. 引用int a;
Int &b=a;注意,引用在定义时候就要初始化
8. 一般每个类单独一个头文件和一个cpp文件,注意定义的时候
一般用来避免重复定义
#ifndef XXXX_H_H
#define XXXX_H_H
……
#endif
#include<iostream>
#include<string>
using namespace std;
class BirthDate
{
public:
BirthDate();
BirthDate(int ,int ,int);
void display();
private:
int year;
int month;
int day;
};
BirthDate::BirthDate() //这个要声明一个,不然会报错.......
{
year=0;
month=0;
day=0;
}
BirthDate::BirthDate(int y,int m,int d)
{
year=y;
month=m;
day=d;
}
void BirthDate::display()
{
cout<<"year:"<<year<<"\tmonth:"<<month<<"\tday:"<<day<<endl;
}
class Teacher
{
public:
Teacher(int ,string ,char);
void display();
private:
int num;
string name;
char sex;
};
Teacher::Teacher(int nu,string nam,char s)
{
num=nu;
name=nam;
sex=s;
}
void Teacher::display()
{
cout <<"num:"<<num<<"\tname:"<<name<<"\tsex:"<<sex<<endl;
}
class Professor:public Teacher
{
public:
Professor(int nu,string na,char s,BirthDate b);
void show();
private:
BirthDate birthday;
};
Professor::Professor(int nu,string na,char s,BirthDate b):Teacher(nu,na,s)
{
birthday = b;
}
void Professor::show()
{
Teacher::display();
birthday.display();
}
int main(void)
{
Teacher t;//会报错,因为没有初始化.....
BirthDate b(1998,2,3);
Professor p(12,"spygg",'M',b);
p.show();
return 0;
}