c++重载(c++重载操作符)

[img]

简介:C++中的重载是指在一个类中定义多个同名函数,但参数列表不同,以便可以根据实际需要进行调用。

多级标题:

一、函数重载

二、运算符重载

三、类型转换重载

四、构造函数和析构函数重载

五、函数模板和类模板重载

内容详细说明:

一、函数重载

函数重载是指在同一作用域中,可以定义相同名称但参数列表不同的两个或多个函数。例如:

```c++

void func(int a);

void func(int a, int b);

void func(double a);

```

C++根据函数名和参数列表来确定调用哪一个函数。调用时必须传入正确的参数列表,否则无法编译通过。

二、运算符重载

运算符重载是指对已有运算符重新进行定义,以适应不同类型的数据之间的运算。例如:

```c++

#include

using namespace std;

class Box {

public:

double length, width, height;

Box operator+(const Box& b) {

Box box;

box.length = this->length + b.length;

box.width = this->width + b.width;

box.height = this->height + b.height;

return box;

}

};

int main() {

Box box1, box2, box3;

box1.length = 1.0;

box1.width = 2.0;

box1.height = 3.0;

box2.length = 4.0;

box2.width = 5.0;

box2.height = 6.0;

box3 = box1 + box2;

cout << "The total length of two boxes is " << box3.length << endl;

return 0;

```

运算符重载是通过定义返回类型为类对象的类成员函数来实现的。

三、类型转换重载

类型转换重载是指在类定义中定义一种类型转换函数,在特定情况下将数据类型强制转换为所需类型。例如:

```c++

class Complex {

public:

double real, imag;

Complex(double r = 0, double i = 0){real = r; imag = i;};

operator int () { return (int)real; }

};

int main() {

Complex c(3.14, 1.59);

int n = c;

cout << "The real part of the complex number is " << n << endl;

return 0;

```

类型转换重载是通过重载类型转换运算符来实现的。

四、构造函数和析构函数重载

构造函数和析构函数可以根据不同的参数列表进行重载。例如:

```c++

#include

using namespace std;

class Egg {

public:

Egg() { cout << "A new egg is hatching!\n"; }

Egg(const Egg& /*egg*/) { cout << "A new egg is hatching!\n"; }

~Egg() { cout << "Oh, the egg is gone.\n"; }

};

int main() {

Egg e1, e2, e3(e1);

return 0;

```

五、函数模板和类模板重载

函数模板和类模板也可以进行重载。例如:

```c++

template

void func(T a) {

cout << "This is a function template." << endl;

template

void func(int a, T b) {

cout << "This is another function template." << endl;

int main() {

func(1);

func(1, 2.0);

return 0;

```

以上就是C++中的重载的相关知识,希望对读者有所帮助。

标签列表