C++重载运算符的几类使用方法
- 格式:docx
- 大小:17.93 KB
- 文档页数:7
C++operator关键字(重载操作符)operator是C++的关键字,它和运算符⼀起使⽤,表⽰⼀个运算符函数,理解时应将operator=整体上视为⼀个函数名。
这是C++扩展运算符功能的⽅法,虽然样⼦古怪,但也可以理解:⼀⽅⾯要使运算符的使⽤⽅法与其原来⼀致,另⼀⽅⾯扩展其功能只能通过函数的⽅式(c++中,“功能”都是由函数实现的)。
⼀、为什么使⽤操作符重载?对于系统的所有操作符,⼀般情况下,只⽀持基本数据类型和标准库中提供的class,对于⽤户⾃⼰定义的class,如果想⽀持基本操作,⽐如⽐较⼤⼩,判断是否相等,等等,则需要⽤户⾃⼰来定义关于这个操作符的具体实现。
⽐如,判断两个⼈是否⼀样⼤,我们默认的规则是按照其年龄来⽐较,所以,在设计person 这个class的时候,我们需要考虑操作符==,⽽且,根据刚才的分析,⽐较的依据应该是age。
那么为什么叫重载呢?这是因为,在编译器实现的时候,已经为我们提供了这个操作符的基本数据类型实现版本,但是现在他的操作数变成了⽤户定义的数据类型class,所以,需要⽤户⾃⼰来提供该参数版本的实现。
⼆、如何声明⼀个重载的操作符?A: 操作符重载实现为类成员函数重载的操作符在类体中被声明,声明⽅式如同普通成员函数⼀样,只不过他的名字包含关键字operator,以及紧跟其后的⼀个c++预定义的操作符。
可以⽤如下的⽅式来声明⼀个预定义的==操作符:class person{private:int age;public:person(int a){this->age=a;}inline bool operator == (const person &ps) const;};实现⽅式如下:inline bool person::operator==(const person &ps) const{if (this->age==ps.age)return true;return false;}调⽤⽅式如下:#includeusing namespace std;int main(){person p1(10);person p2(20);if(p1==p2) cout<<”the age is equal!”< return 0;}这⾥,因为operator ==是class person的⼀个成员函数,所以对象p1,p2都可以调⽤该函数,上⾯的if语句中,相当于p1调⽤函数==,把p2作为该函数的⼀个参数传递给该函数,从⽽实现了两个对象的⽐较。
如何获得新知识英语作文Expanding the Horizons of Knowledge: Strategies for Acquiring New Information.In an era characterized by rapid technological advancements and a deluge of information, the pursuit of knowledge has become increasingly essential for personal growth and societal progress. Acquiring new knowledge empowers us to navigate the complexities of the modern world, make informed decisions, and contribute meaningfully to our communities. However, the sheer volume of information available today can be overwhelming, andfinding effective strategies to filter and absorb knowledge can be a challenge.1. Active Reading and Critical Thinking:Engaging in active reading involves more than simply glancing over a text; it requires actively interrogating the material, questioning its assumptions, and seekingconnections with existing knowledge. Critical thinking skills enable us to analyze, evaluate, and synthesize information, separating facts from opinions and identifying biases. By questioning the author's purpose, evidence, and reasoning, we develop a deeper understanding of the subject matter.2. Immersive Learning Experiences:Immersive learning experiences provide opportunities to engage with knowledge in a tangible and interactive way. These experiences can take various forms, such as attending lectures, participating in workshops, conducting research, or engaging in hands-on activities. By immersing ourselves in the learning environment, we enhance retention andfoster a deeper connection with the material.3. Seek Out Diverse Perspectives:Exposing ourselves to multiple perspectives enriches our understanding by providing us with a broader context and challenging our existing beliefs. Reading from diversesources, including books, articles, podcasts, and online forums, allows us to consider different viewpoints and gain a more comprehensive picture of the topic. Engaging in respectful discussions with individuals from different backgrounds also promotes intellectual growth.4. Leverage Technology for Learning:Technology has opened up numerous avenues for knowledge acquisition. Online learning platforms, educational apps, and virtual reality simulations provide convenient and interactive ways to explore new subjects. These tools often offer personalized learning experiences tailored to individual interests and learning styles, enabling us to learn at our own pace and delve into areas that spark our curiosity.5. Practice Active Recall and Spaced Repetition:Active recall involves regularly testing our knowledge through methods such as flashcards, quizzes, or teaching the material to others. This process strengthens memory byforcing us to retrieve information from long-term storage. Spaced repetition involves reviewing previously learned material at increasing intervals, which helps to solidify knowledge and prevent forgetting.6. Set Learning Goals and Track Progress:Defining specific learning goals provides direction and motivation for knowledge acquisition. By setting clear objectives, we can prioritize our efforts and track our progress. Regular self-assessment helps us identify areas where further learning is needed and provides a sense of accomplishment as we achieve our goals.7. Engage in Meaningful Connections:Connecting new knowledge to existing experiences and knowledge structures helps to make it more personally relevant and memorable. By reflecting on how the new information relates to our personal values, beliefs, and past experiences, we create meaningful associations that enhance retention.8. Foster a Growth Mindset:Adopting a growth mindset, where we embrace challenges and view mistakes as opportunities for learning, is essential for continuous knowledge acquisition. By believing that our abilities can be developed through effort and persistence, we cultivate a lifelong love of learning.9. Find a Knowledge Partner or Mentor:Learning alongside a knowledge partner or mentor can provide valuable guidance and support. Sharing ideas, challenging each other's perspectives, and holding ourselves accountable for our learning progress can accelerate knowledge acquisition and foster a sense of community.10. Engage in Real-World Applications:Applying new knowledge to real-world situations notonly reinforces learning but also provides opportunities for practical implementation. By actively using the information we acquire, we refine our understanding and discover new ways to solve problems or create value.In conclusion, acquiring new knowledge is an ongoing journey that requires an inquisitive mindset, effective strategies, and a commitment to continuous learning. By embracing these practices, we unlock our potential to navigate the complexities of the modern world, make a meaningful impact on our communities, and live fulfilling and intellectually stimulating lives.。
operator 函数Operator 函数,也叫重载运算符函数,是 C++ 中一种特殊的成员函数。
它们用于自定义数据类型之间的运算,实现运算符对这些数据类型的支持,为C++语言的多样性和灵活性提供了支持。
在C++中,它提供了一组预定义的运算符,它们表示算术、比较、位、逻辑操作等等。
重载运算符函数的目的是为了扩展这个集合,通过定义自定义的运算符,而且也支持成员函数和非成员函数的形式。
那么,什么情况下需要使用operator 函数呢?通常,当两种或两种以上的自定义类型需要进行操作时,我们需要使用operator 函数。
下面将介绍operator 函数常见的形式和具体应用。
1. 一元算术运算符一元算术运算符表示只有一个参数的运算,包括正号、负号、自增、自减运算符。
如果我们需要对自定义类型进行一元运算,需要实现operator+,operator-,operator++ 和 operator-- 函数。
示例代码如下:```c++class MyNum {public:int value;MyNum operator+(const MyNum& num) {MyNum result;result.value = value + num.value;return result;}MyNum operator-() {MyNum result;result.value = -value;return result;}MyNum operator++() {value++;return *this;}MyNum operator--(int) {MyNum result = *this;value--;return result;}};```2. 二元算术运算符二元算术运算符表示需要两个参数的运算,包括加、减、乘、除、取模等等。
如果我们需要对自定义类型进行二元运算,需要实现operator+,operator-,operator*,operator/ 和 operator% 函数。
c++ 结构operator用法摘要:1.C++结构体的基本概念2.结构体的成员访问和修改方法3.结构体的运算符重载4.结构体的函数重载5.结构体的实例正文:C++结构体是一种复合数据类型,它可以包含多个不同类型的成员变量。
结构体主要用于存储具有多个属性的实体,例如学生的姓名、年龄、性别等。
结构体在C++中是一种十分重要的数据结构,掌握好结构体的使用方法对于C++编程至关重要。
一、结构体的基本概念结构体是一种用户自定义的数据类型,它可以包含多个成员变量。
结构体定义的基本语法如下:```struct 结构体名{数据类型1 成员变量名1;数据类型2 成员变量名2;//...};```二、结构体的成员访问和修改方法结构体定义完成后,可以通过以下方法访问和修改结构体成员:1.访问结构体成员:使用点运算符`.`,例如`struct 体名。
成员变量名`。
2.修改结构体成员:使用赋值运算符`=`,例如`struct 体名。
成员变量名= 值`。
三、结构体的运算符重载C++中的运算符重载是一种让程序员自定义运算符行为的技术。
结构体可以重载运算符`+`、`-`、`*`、`/`等,以实现对结构体成员的运算。
运算符重载的语法如下:```struct 结构体名{//...struct 结构体名operator+(const struct 结构体名& other);struct 结构体名operator-(const struct 结构体名& other);struct 结构体名operator*(const struct 结构体名& other);struct 结构体名operator/(const struct 结构体名& other);//...};```四、结构体的函数重载结构体可以重载函数,包括成员函数和友元函数。
函数重载可以让程序员根据需要实现不同的功能。
函数重载的语法如下:```struct 结构体名{//...void function 名(参数列表);//...};```五、结构体的实例下面是一个结构体示例,定义了一个名为`Student`的结构体,包含姓名、年龄和性别三个成员变量:```struct Student{std::string name;int age;char gender;};```可以通过以下方法创建`Student`结构体的实例:```Student student1("张三", 20, "M");```以上就是C++结构体的基本概念、成员访问和修改方法、运算符重载、函数重载以及实例的详细讲解。
在许多编程语言中,你可以通过重载运算符来定义用户自定义类型(例如类或结构体)的行为。
这样,你可以自定义类在进行运算时的行为。
下面是一个简单的示例,展示了如何在C++中重载加法运算符(+):#include <iostream>class Pair {private:int first;int second;public:Pair(int a, int b) : first(a), second(b) {}// 重载加法运算符Pair operator+(const Pair& other) {Pair result(first + other.first, second + other.second);return result;}// 为了方便输出,可以重载流插入运算符friend std::ostream& operator<<(std::ostream& os, const Pair& pair) {os << "(" << pair.first << ", " << pair.second << ")";return os;}};int main() {Pair pair1(1, 2);Pair pair2(3, 4);Pair result = pair1 + pair2;std::cout << "pair1: " << pair1 << std::endl;std::cout << "pair2: " << pair2 << std::endl;std::cout << "result: " << result << std::endl;return 0;}在这个例子中,Pair 类中重载了加法运算符+。
【C++】C++函数重载的总结函数重载: 出现在相同作⽤域中的两个函数,如果具有相同的名字⽽形参表不同,则称为重载函数(overloaded function)。
⼀定要注意函数重载的两个关键词:形参列表和作⽤域。
任何程序有且仅有⼀个main函数的实例,main函数不能重载。
对于函数重载来说,它们应该在形参数量和形参类型上有所不同。
下⾯论述形参列表和作⽤域对函数重载的影响。
函数重载与形参列表 函数重载和函数声明的区别: 如果两个函数声明的返回类型和形参表完全匹配,则将第⼆个声明视为第⼀个的重复声明。
如果两个函数的形参列表相同(参数个数和类型)相同但是返回类型不同,那么第⼆个函数的声明将会出现编译错误。
函数不能仅仅基于不同的返回类型⽽实现重载。
基于const形参的重载: 当参数是⾮引⽤形参时,形参与const形参的两个同名函数不能构成函数重载。
下⾯的第⼆个函数只是第⼀个函数的重复声明。
1 A func(B);2 A func(const B); // 重复声明 仅当形参是引⽤或指针是,形参是否为const才有影响。
A func(B&);A func(const B&) //基于const引⽤形参的重载A func(B*);A func(const B*); //基于const指针形参的重载可基于函数的引⽤形参是指向const对象还是指向⾮const对象,实现函数重载。
将引⽤形参定义为const来重载函数是合法的,因为编译器可以根据实参是否为const确定调⽤哪⼀个函数。
如果实参为const对象,那么将调⽤const引⽤形参的版本。
如果实参为⾮const对象,⾮const对象既可以⽤于初始化const引⽤,也可以⽤于初始化⾮const引⽤。
但是将const引⽤初始化为⾮const对象,需要转换,因为⾮const形参的初始化则是精确匹配。
对于指针形参也是如出⼀辙。
如果实参是const对象,则调⽤带有const*类型形参的函数。
operator在c++中的用法operator在C++中是一个关键字,它可以用来定义特殊的运算符重载函数。
它的定义形式如下:operator op(arguments);其中op是指要重载的运算符,而arguments是该运算符的操作数,可以是任意的类型,但是操作数的类型必须一致,如果要重载一元运算符,操作数只有一个,如果要重载二元运算符,操作数有两个。
operator的主要作用是将一个函数作为一元运算符或二元运算符来使用,以此来实现运算符重载,使得原本的运算符获得新的功能。
operator还可以被用于定义模板函数。
operator的使用主要依赖类的定义,因此它只能用在类的成员函数中。
由于operator的作用是对运算符进行重载,所以它本质上是一个函数,可以有函数的一些特性,如返回值类型检测,静态成员函数,引用参数,异常处理等。
需要注意的是,operator只能重载已有的运算符,不可以自定义新的运算符。
也就是说,op参数只能是已有的运算符,不能使用自定义的运算符。
例如,下面是一个将operator用于重载运算符的例子:class A{public:int a;A(int val) : a(val) {}// 重载+运算符,使其可以用于A的两个对象A operator+(const A& b){return A(a + b.a);}};int main(){A a1(1);A a2(2);A a3 = a1 + a2;cout << a3.a << endl;return 0;}以上程序将operator用于重载+运算符,当执行 a3 = a1 + a2 这条语句时,实际上调用的是A::operator+() 函数,返回值是一个新的A对象,其值为a1.a + a2.a的和。
c语言中operator的用法在C语言中,运算符(operator)是用于执行各种数学或逻辑操作的特殊符号。
C语言提供了多种运算符,以便程序员可以执行不同的计算和操作。
1. 算术运算符:算术运算符用于执行基本的数学计算,包括加法、减法、乘法、除法和取模等操作。
例如,加法运算符(+)用于将两个数相加,减法运算符(-)用于将一个数减去另一个数。
2. 关系运算符:关系运算符用于比较两个值之间的关系,可以返回一个布尔值(true或false)。
比较运算符包括等于(==)、不等于(!=)、大于(>)、小于(<)、大于等于(>=)和小于等于(<=)等。
3. 逻辑运算符:逻辑运算符用于在条件语句中组合或改变不同条件的逻辑关系。
逻辑运算符包括逻辑与(&&)、逻辑或(||)和逻辑非(!)。
逻辑与运算符返回true仅当两个条件都为true时,逻辑或运算符返回true只要有一个条件为true,逻辑非运算符返回相反的结果。
4. 赋值运算符:赋值运算符用于将值赋给变量。
常见的赋值运算符是等于号(=)。
5. 位运算符:位运算符用于执行对二进制位进行操作的操作。
它们可以用于位移、按位与、按位或和按位异或等操作。
例如,左移运算符(<<)将二进制数向左移位。
6. 条件运算符:条件运算符(?:)是C语言中唯一的三元运算符。
它根据某个条件的结果选择两个值中的一个。
7. 其他运算符:除了上述常见的运算符外,C语言还提供了其他一些特殊的运算符,如sizeof运算符用于返回数据类型或变量的大小,取地址运算符(&)用于获取变量的地址,取值运算符(*)用于访问指针指向的值等。
在使用运算符时,需要注意运算符的优先级和结合性,以确保表达式的计算顺序符合预期。
此外,还应遵循C语言的语法规则和最佳实践,以确保代码的可读性和可维护性。
总而言之,C语言中的运算符提供了丰富的功能,可以进行各种数学和逻辑运算。
一、实验目的1. 理解运算符重载的概念和原理。
2. 掌握C++中运算符重载的方法和规则。
3. 通过实例,实现自定义类型对运算符的重载。
4. 分析运算符重载在实际编程中的应用和优势。
二、实验环境1. 编程语言:C++2. 开发环境:Visual Studio 20193. 操作系统:Windows 10三、实验内容1. 运算符重载的概念和原理2. 运算符重载的方法和规则3. 自定义类型运算符重载实例4. 运算符重载的实际应用四、实验步骤1. 概念和原理运算符重载是指为已有的运算符赋予新的功能,使其能够应用于自定义类型的数据。
在C++中,运算符重载可以通过成员函数或友元函数实现。
2. 方法和规则- 成员函数重载:在自定义类型中定义一个成员函数,该函数的名称与要重载的运算符相同。
- 友元函数重载:在自定义类型外部定义一个友元函数,该函数的名称与要重载的运算符相同,并在函数声明中添加类名和作用域解析运算符。
运算符重载规则:- 运算符重载的函数必须返回与操作数相同的类型。
- 运算符重载的函数不能改变原有运算符的操作数个数。
- 运算符重载的函数不能改变原有运算符的优先级。
- 运算符重载的函数不能改变原有运算符的结合性。
3. 自定义类型运算符重载实例假设我们有一个自定义类型`Point`,表示二维平面上的一个点,其坐标为`(x, y)`。
```cppclass Point {public:int x, y;Point(int x, int y) : x(x), y(y) {}// 成员函数重载加法运算符Point operator+(const Point& p) const {return Point(x + p.x, y + p.y);}// 友元函数重载加法运算符friend Point operator-(const Point& p1, const Point& p2);};// 实现友元函数重载减法运算符Point operator-(const Point& p1, const Point& p2) {return Point(p1.x - p2.x, p1.y - p2.y);}```4. 运算符重载的实际应用运算符重载在实际编程中具有以下优势:- 提高代码可读性:使用自定义类型时,可以像操作基本数据类型一样使用运算符,提高代码的可读性。
enum重载等号运算符在C++中,enum是一种枚举类型,用于定义一组具有离散取值的常量。
尽管enum类型的默认行为已经足够方便,但有时我们可能需要为其添加一些自定义的操作符。
其中一个常见的需求是重载等号运算符,以便我们可以在enum类型之间进行比较。
为了重载等号运算符,我们需要将其定义为enum类型的成员函数。
下面是一个示例:```cppenum class Color { RED, GREEN, BLUE };bool operator==(Color a, Color b) {return static_cast<int>(a) == static_cast<int>(b);}```在这个例子中,我们定义了一个enum类型Color,并为其重载了等号运算符。
在重载函数中,我们将enum类型的值转换为整数,然后比较它们的值。
如果两个enum值相等,则返回true,否则返回false。
现在我们可以使用重载后的等号运算符来比较两个Color类型的值了:```cppColor color1 = Color::RED;Color color2 = Color::GREEN;if (color1 == color2) {// 代码不会执行到这里} else {// 进入这个分支}```在上面的代码中,我们将color1和color2分别赋值为Color::RED 和Color::GREEN,然后使用重载后的等号运算符进行比较。
由于这两个值不相等,所以代码将进入else分支。
通过重载等号运算符,我们可以轻松地比较enum类型的值,使代码更加简洁和可读。
这种技巧在处理状态机、选项和标志等场景中特别有用。
总结一下,重载等号运算符可以使我们在enum类型之间进行比较,使代码更加简洁和可读。
在重载时,我们需要将等号运算符定义为enum类型的成员函数,并在其中进行值的比较。
通过合理使用重载等号运算符,我们可以提高代码的可维护性和可读性,让程序更加易于理解和扩展。
c不能重载的运算符-回复c语言中有一些运算符是无法进行重载的,即无法改变其原有的语义和操作方式。
这些不能重载的运算符包括以下几种:1. 赋值运算符(=):赋值运算符是最基本的运算符之一,用于将一个值赋给变量。
在C中,赋值运算符是不可重载的,其行为无法进行改变。
这是因为赋值运算符的语义已经由语言规范明确定义,重载赋值运算符可能会导致代码的可读性和可维护性降低。
2. 成员访问运算符(.和->):成员访问运算符用于访问结构体或类的成员变量和成员函数。
在C中,这两个运算符也是不可重载的。
这是因为结构体和类的成员布局是由编译器处理的,重载这两个运算符可能会导致无法正确访问成员变量和成员函数。
3. 下标运算符([]):下标运算符用于访问数组或类的重载了下标运算符的对象的元素。
在C中,下标运算符也是不可重载的。
这是因为C语言的数组和类似数组的结构体没有内置的下标处理机制,重载下标运算符可能会导致访问越界或者出现其他意想不到的问题。
4. 函数调用运算符(()):函数调用运算符用于调用函数或重载了函数调用运算符的对象的操作符函数。
在C中,函数调用运算符也是不可重载的。
这是因为C语言的函数调用机制是由编译器和操作系统处理的,重载函数调用运算符可能会导致无法正确调用函数或者出现其他问题。
5. 三个由语言规范定义的运算符:sizeof、?:和. (点操作符):这三个运算符有特定的语法和语义,无法进行重载。
sizeof运算符用于获取类型或对象的大小,?:运算符用于条件选择,点操作符用于访问成员变量或成员函数。
上述的这些运算符在C语言中是不可变的,它们的行为由语言规范明确定义,并且编译器对其进行了特殊处理。
重载这些运算符可能会导致代码的不可预测行为和难以维护的错误。
因此,C语言中禁止对这些运算符进行重载。
对于需要对这些运算符进行自定义操作的需求,可以使用其他方法来实现,如使用函数或宏来替代运算符的功能。
此外,在其他编程语言中,如C++和Java,一些运算符是可以进行重载的,开发者可以根据自己的需求对运算符进行自定义操作。
能用友元函数重载的运算符
友元函数是一种特殊的函数,它可以访问类的私有成员。
在C++中,我们可以使用友元函数重载运算符来完成一些特殊的操作。
使用友元函数重载运算符的好处在于可以直接使用运算符来操
作对象,而不需要调用对象的成员函数。
例如,我们可以使用加号运算符直接将两个对象相加,而不需要调用对象的成员函数。
常见的可以用友元函数重载的运算符包括加号、减号、乘号、除号、等于号、小于号、大于号等等。
这些运算符可以被重载为友元函数,以实现特殊的操作。
需要注意的是,友元函数重载运算符时,我们需要将友元函数声明为类的友元函数,以便访问类的私有成员。
同时,我们还需要遵守运算符重载的一些规则,例如运算符的操作数个数、操作数类型等等。
总之,使用友元函数重载运算符可以让我们更方便地操作对象,提高代码的可读性和可维护性。
- 1 -。
1. 非运算符重载实现复数的加法运算 //非运算符重载实现复数的加法运算 //complex.h #include #ifndef COMPLEX_H #define COMPLEX_H class complex { public: complex(); doublegetreal(); doublegetimag(); voidsetreal(double); voidsetimag(double); void display(); private: double real; double image; }; #endif //complex.cpp #include #include"complex.h" complex::complex() { real = 0; image = 0; } void complex::setreal(double r) { real = r; }
void complex::setimag(double i) { image = i; }
double complex::getreal() { return real; } double complex::getimag() { return image; } void complex::display() { cout<<"the result is\n"<} //test.cpp #include #include"complex.h" complex add(complex comp1,complex comp2); complex sub(complex comp1,complex comp2); void main() { complex c1,c2,c3,c4; c1.setreal(2.0); c1.setimag(3.0); c2.setreal(1.0); c2.setimag(4.0); c3 = add(c1,c2); cout<<"c3 = c1 + c2 , "; c3.display(); c4 = sub(c1,c2); cout<<"c4 = c1 - c2 ,"; c4.display(); } complex add(complex comp1,complex comp2) { complex temp; temp.setreal(comp1.getreal() + comp2.getreal()); temp.setimag(comp1.getimag() + comp2.getimag()); return temp; } complex sub(complex comp1,complex comp2) { complex temp; temp.setreal(comp1.getreal() - comp2.getreal()); temp.setimag(comp1.getimag() - comp2.getimag()); return temp; }
2. 运算符重载作为类的成员函数
//运算符重载作为类的成员函数 //complex.h #include #ifndef COMPLEX_H #define COMPLEX_H class complex { public: complex(double = 0.0,double = 0.0); complex operator+ (const complex &); complex operator- (const complex &); complex& complex::operator= (const complex &); void display(); private: double real; double image; }; #endif //complex.cpp #include #include"complex.h" complex::complex(double r,doublei) { real = r; image = i; } complex complex::operator+(const complex &c2)//定义重载运算符函数 { complex c; c.real = real + c2.real; c.image = image + c2.image; return c; } complex complex::operator-(const complex &c2)//定义重载运算符函数 { complex c; c.real = real - c2.real; c.image = image - c2.image; return c; } complex& complex::operator= (const complex &right) { real = right.real; image = right.image; return *this; } void complex::display() { cout<<"the result is\n"<} //test.cpp #include #include"complex.h" double main( ) { complex c3,c4,c1(3.0,4.0),c2(5.0,1.0); cout<<"c1="; c1.display(); cout<<"c2="; c2.display(); c3=c1+c2; //运算符+用于复数运算 cout<<"c1+c2=" 3. 运算符重载作为类的友元函数 //运算符重载作为类的友元函数 //complex.h #include #ifndef COMPLEX_H #define COMPLEX_H class complex { friend complex operator +(complex &c1,complex &c2);//重载函数作为类的友元函数 friend complex operator -(complex &c1,complex &c2);//重载函数作为类的友元函数 public: complex(double r= 0.0 ,double i = 0.0); void display(); private: double real; double image; }; #endif //complex.cpp #include #include"complex.h" complex::complex(double r,doublei) { real=r; image=i; } void complex::display() { cout<<"the result is "<} complex operator +(complex &c1,complex &c2) { complex c3; c3.real=c1.real + c2.real ; c3.image = c1.image +c2.image ; return c3; } complex operator -(complex &c1,complex &c2) { complex c3; c3.real=c1.real - c2.real ; c3.image = c1.image -c2.image ; return c3; } //test.cpp #include #include"complex.h" int main() { complex c1(2.0,1.0),c2(1.0,3.0),c3,c4; cout<<"c1="; c1.display(); cout<<"c2="; c2.display(); c3=c1+c2; c4=c1-c2; c3.display(); c4.display(); return 0; } 4.运算符重载作为类的非成员非友元函数 //运算符重载作为类的非成员非友元函数 //complex.h