# 重载与多态

### 运算符重载

#### 重载形式

{

}

**实现‘+’的重载**
#include<iostream>
using namespace std;
class counter {
private:
float a;
public:
counter(float a=0):a(a){}
counter operator+(counter& c)const {   **//定义为类的非静态成员函数**
return counter(a + c.a);
}
//friend counter operator+(counter& c1,counter& c2);  **//定义为非成员函数**
void print()const {
cout <<"和为:"<< a << endl;

}
};
/*counter operator+(counter& c1, counter& c2) {
return counter(c1.a + c2.a);
}*/
int main() {
float i, j;
cout << "输入要相加的两个数：";
cin >> i >> j;
counter c1(i),c2(j),c3;
c3 = c1 + c2;
c3.print();
return 0;
}


### 虚函数

#include<iostream>
using namespace std;
class BaseClass {
public:
virtual void fun1() {
cout << "调用BaseClass::fun1" << endl;
}
void fun2() {
cout << "调用BaseClass::fun2" << endl;
}
};
class DerivedClass :public BaseClass {![](https://img2018.cnblogs.com/blog/1784291/201910/1784291-20191026225036711-1317513051.png)

public:
void fun1() {
cout << "调用DerivedClass::fun1" << endl;
}
void fun2() {
cout << "调用DerivedClass::fun2" << endl;
}
};
void print(BaseClass *p) {
p->fun1();
p->fun2();
}

int main() {
DerivedClass c2;

print(&c2);

}


### 抽象类

#include<iostream>
using namespace std;
class base1 {
public:
virtual void display()const = 0;//定义纯虚函数

};
class base2:public base1{
public:
void display()const {
cout << "baseclass	\n";
}
};
void print(base1* p) {
p->display();
}
int main() {
//#include<iostream>
using namespace std;
class base1 {
public:
virtual void display()const = 0;

};
class base2:public base1{
public:
void display()const {
cout << "baseclass	\n";
}
};
void print(base1* p) {
p->display();
}
int main() {
//baseclass1 A1;
base2 A2;
print(&A2);//与虚函数相同，通过指针或引用来调用纯虚函数
return 0;

}


### 派生类的虚函数或纯虚函数通过与基类的虚函数或纯虚函数返回类型，函数名，形参类型数量自动确定

posted @ 2019-10-26 23:36  牙齿白的  阅读(1136)  评论(0编辑  收藏  举报