1.重载
重载构成的条件:函数的参数类型,参数个数不同。
#include <iostream>
class Point {
public:
int x;
int y;
Point() {
x = 0;
y = 0;
}
Point(int a, int b) {
x = a;
y = b;
}
};
Point pnt(5,5);
两个构造函数,参数个数不同。调用的函数取决于传值不同。在函数重载时,要注意函数中带有默认参数的这种情况。
2.继承
避免代码的冗余,C++实现了类的继承机制,父类称之为基类,子类也称之为派生类;
#include <iostream>
class Animal {
public:
void eat() {
cout << "animal eat" << endl;
}
void sleep() {
cout << "animal sleep" << endl;
}
void breath() {
cout << "animal breath" << endl;
}
};
class Fish :public Animal {
};
void main() {
Animal an;
Fish fh;
an.eat();
fh.eat();
}
上述代码中,鱼子类继承自动物父类,拥有父类的吃、睡、呼吸函数。
构造fh对象时,animal类的构造函数首先被调用;析构时,最后析构父类。
3. 虚函数和多态性
#include <iostream>
class Animal {
public:
void eat() {
cout << "animal eat" << endl;
}
void sleep() {
cout << "animal sleep" << endl;
}
virtual void breath() {
cout << "animal breath" << endl;
}
};
class Fish :public Animal {
void breath() {
cout << "fish breath" << endl;
}
};
void main() {
Animal an;
Fish fh;
an.eat();
fh.eat();
}
在父类的函数名前加上virtual关键字,便构成了虚函数。这就是多态性,当C++编译器在编译的时候,发现父类的breath函数是虚函数时,采用迟邦定技术,也就是编译时并不确定具体调用的函数,而是在运行时,根据对象的类型来确认调用的是哪一个函数。
在派生类中重写该函数,如果运行时对象时派生类,就调用派生类的函数;如果是基类则调用基类的函数。
派生类和基类的某一函数,如果函数名,参数列表都一致,则是覆盖,或者叫做重写(override);构成覆盖的条件是:
1)基类函数必须是虚函数
2)发生覆盖的两个函数分别位于派生类和基类中
3)函数名称与参数列表完全一致
4.函数的隐藏
#include <iostream>
class Animal {
public:
void eat() {
cout << "animal eat" << endl;
}
void sleep() {
cout << "animal sleep" << endl;
}
void breath() {
cout << "animal breath" << endl;
}
};
class Fish :public Animal {
void breath() {
cout << "fish breath" << endl;
}
};
void main() {
Animal an;
Fish fh;
an.eat();
fh.eat();
}
派生类中的breath函数与基类的breath函数完全一样,不同的是基类函数不是虚函数,这种就称之为隐藏,也叫做重定义。
此时,要调用基类被隐藏的函数,可通过基类名::函数的形式。
5.例子
#include <iostream>
class Base
{
public:
Base()
{
printf("I am Base()\n");
}
virtual ~Base()
{
printf("I am ~Base()\n");
}
public:
virtual void SayHello()
{
printf("Hello Base\n");
}
void SayWorld()
{
printf("World Base\n");
}
};
class Derived : public Base
{
public:
Derived()
{
printf("I am Derived()\n");
}
virtual ~Derived()
{
printf("I am ~Derived()\n");
}
public:
void SayHello();
void SayWorld();
};
void Derived::SayHello()
{
printf("Hello Derived\n");
}
void Derived::SayWorld()
{
printf("World Derived\n");
}
int main(void)
{
Base *b1 = new Base;
Base *b2 = new Derived;
Derived *d = new Derived;
b1->SayHello();
b1->SayWorld();
b2->SayHello();
b2->SayWorld();
d->SayHello();
d->SayWorld();
delete d;
delete b2;
delete b1;
d = NULL;
b2 = NULL;
b1 = NULL;
while (1);
return 0;
}
结果是:
I am Base()
I am Base()
I am Derived()
I am Base()
I am Derived()
Hello Base
World Base
Hello Derived
World Base
Hello Derived
World Derived
I am ~Derived()
I am ~Base()
I am ~Derived()
I am ~Base()
I am ~Base()