C++重载运算符的几类使用方法

合集下载

C++operator关键字(重载操作符)

C++operator关键字(重载操作符)

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作为该函数的⼀个参数传递给该函数,从⽽实现了两个对象的⽐较。

C--程序设计--第10章-多态性及虚函数

C--程序设计--第10章-多态性及虚函数

使用重载函数注意:
不要使用重载函数描述不相干的函数 在类中,构造函数和普通成员函数均可以
重载 避免与函数的默认参数产生二义性
二、运算符重载
运算符重载(operate overloading)就是 赋予已有的运算符多重含义。
运算符重载实质是函数重载,运算符重载 的选择与函数重载类似,会根据运算符的 操作数的类型、个数和顺序来进行运算符 函数的选择。
#include<iostream.h> str#iinngc:l:usdter<isntgr(icnhga.rh>*s) v{}ossccsssc{s{{ittohtttolsstlsssls*drruarrrueptrepttepsi1trii3tc{pn=rin=rrn=pmn.<nn.<lprgncngncign=agp<*ggp<auitepgtepnte'irssrssbv\hwy:hwyghwnsit1ssitsla0=(:=(:=(tnr=ttnrit'scssscs:sc)rt1"rrt3scesss~ivci;thpt1hpsih1(.T23(.t::tttsnohn}ra,r.a,tza()gh(()grrrrttiatlrsilrsrer";eass;eiiiirdre[)ne[1i;[Ttt1ttnnnniglnl;gnl.nlhl)rlggggnep*e(e}(gesgeiei;2e(((gtrsnsnstnp(nsns)ncsi(lipg)gthg)ig(;(htn)en;t;tr;t;nti)a)artnthhih}ths<<ri{((;+n++<p<snd))}1g1s1aere*ige;]]i]nonszl{{;&;z;ddgd)&eercseelrl;s=teo1)m;a;/18etu)om/)0ut..;)构sr<""/;pn<造);//;s;/复}lp函构e<制n<数造ge构tn函hd造;l数};重} 载

谭浩强《C++程序设计》课件 第10章

谭浩强《C++程序设计》课件 第10章

通过运算符重载,扩大了 通过运算符重载,扩大了C++已有运算符的作用范 已有运算符的作用范 使之能用于类对象. 围,使之能用于类对象. 运算符重载对C++有重要的意义,把运算符重载和 有重要的意义, 运算符重载对 有重要的意义 类结合起来,可以在C++程序中定义出很有实用意 类结合起来,可以在 程序中定义出很有实用意 义而使用方便的新的数据类型.运算符重载使C++ 义而使用方便的新的数据类型.运算符重载使 具有更强大的功能,更好的可扩充性和适应性, 具有更强大的功能,更好的可扩充性和适应性,这 最吸引人的特点之一. 是C++最吸引人的特点之一. 最吸引人的特点之一
c.imag=imag+c2.imag; return c;} void Complex∷display( ) //定义输出函数 ∷ 定义输出函数 {cout<<〃(〃<<real<<〃,〃<<imag<<〃i)〃<<endl;} int main( ) {Complex c1(3,4),c2(5,-10),c3; c3=plex_add(c2); cout<<〃c1=〃; c1.display( ); cout<<〃c2=〃; c2.display( ); cout<<〃c1+c2=〃; c3.display( ); return 0; }
Complex operator+ (Complex& c1,Complex& c2);
在定义了重载运算符的函数后,可以说: 在定义了重载运算符的函数后,可以说: 函数 operator+重载了运算符 . 重载了运算符+. 重载了运算符 为了说明在运算符重载后,执行表达式就是调用函 为了说明在运算符重载后, 数的过程, 数的过程,可以把两个整数相加也想像为调用下面 的函数: 的函数:

c语言重定义函数

c语言重定义函数

如何获得新知识英语作文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.。

重载操作符

重载操作符

74:重载操作符、类成员函数还是友元函数
运算符重载两种形式
• (1)定义类的成员函数(2)定义类的友元函数
注意事项
• (1)一般作为类的成员函数,其形参操作符看起来比操作数数 目少1.因为作为成员函数的操作符存在一个隐含的this形参, 限定为第1个操作数。 • (2)重载一元操作符,如果作为成员函数就没有形参,作为友 元函数就有一个形参。 • (3)重载二元操作符,如果作为成员函数有一个形参,作为友 元函数有两个形参。 • (4)一般将关系和算术操作符声明为友元函数,将赋值操作符 定义为成员函数。
以上两种实现方式随存在一定的差异,但是其功能基本相同。 然而出现一下情况 CComplex d=CComplex(1,2); CComplex sum= 2+d;? 采用成员函数则不通过,友员函数则可以通过。 如果运算符采用友员函数实现,左右参数都可进行隐式转换, 而如果采用成员函实现则只允许右参数隐式转换。 运算符友员函数实数现时,操作数的隐式转换会增加程序执行 成本。
74:重载操作符、类成员函数还是友元函数
(1) 双目运算符重载为类的成员函数时,函数只显式说 明一个参数,该形参是运算符的右操作数。 (2) 前置单目运算符重载为类的成员函数时,不需要显 式说明参数,即函数没有形参。 (3) 后置单目运算符重载为类的成员函数时,函数要带 有一个整型形参。 调用成员函数运算符的格式如下: <对象名>.operator <运算符>(<参数>) 它等价于 <对象名><运算符><参数> 例如:a+b等价于a.operator +(b)。一般情况下,我们 采用运算符的习惯表达方式。
74:重载操作符、类成员函数还是友元函数

operator 函数

operator 函数

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用法

c++ 结构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++结构体的基本概念、成员访问和修改方法、运算符重载、函数重载以及实例的详细讲解。

pair重载运算符

pair重载运算符

在许多编程语言中,你可以通过重载运算符来定义用户自定义类型(例如类或结构体)的行为。

这样,你可以自定义类在进行运算时的行为。

下面是一个简单的示例,展示了如何在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 类中重载了加法运算符+。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

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="

相关文档
最新文档