1.类函数的重载特性
类函数的重载特性就是我们可以在类里面定义同名的函数,但是参数不同的函数。
class student
{
public :
char name[60];
int age;
void test();
void test(int a);
private :
int haha;
};
重载函数在调用的时候,会根据参数的类型,然后去匹配相应的函数进行调用。
2.构造函数和析构函数
析构函数:假如我们定义了析构函数,当对象被删除或者生命周期结束的时候,就会触发析构函数。
构造函数:假如我们定义了构造函数,当对象被创建的时候,就会触发构造函数。
我们要怎么定义构造函数和析构函数?
1.析构函数和构造函数的名字必须和类名一模一样。
2.析构函数要在前面加上一个~
3.构造函数可以重载,析构函数不可以。
4.带参数的构造函数写法,在对象名后加(),参数填在()里。
3.类的继承
类的继承允许我们在新的类里面继承父类的public还有protected部分,private是不能被继承。
当我们觉得这个类不好的时候,可以使用类的继承,添加我们需要的功能。
格式
class 儿子 :pubilic 爸爸{
public :
/
protected:
};
例子:
class mystudeng:public student
{
public:
int grade;
};
在子类里面去访问父类的成员,也是通过.和->来访问的。
4.虚函数和纯虚函数
虚函数:有实际定义,允许派生类对它进行覆盖式的替换,用virtual来修饰。
纯虚函数:没有实际定义的虚函数就是纯虚函数。
虚函数优点:可以预留接口,实现分工合作。
怎么定义一个虚函数?
虚函数例子
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
virtual int area()
{
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape{
public:
Rectangle( int a=0, int b=0):Shape(a, b) { }
int area ()
{
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
class Triangle: public Shape{
public:
Triangle( int a=0, int b=0):Shape(a, b) { }
int area ()
{
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};
// 程序的主函数
int main( )
{
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
// 存储矩形的地址
shape = &rec;
// 调用矩形的求面积函数 area
shape->area();
// 存储三角形的地址
shape = &tri;
// 调用三角形的求面积函数 area
shape->area();
return 0;
}
纯虚函数例子
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
// pure virtual function
virtual int area() = 0;
};
= 0 告诉编译器,函数没有主体,上面的虚函数是纯虚函数。