浅谈C++类型转化(运算符重载函数)和基本运算符重载(自增自减)

2025-05-27 0 88

类型转化运算符重载函数)

用转换构造函数可以将一个指定类型的数据转换为类的对象。但是不能反过来将一个类的对象转换为一个其他类型的数据(例如将一个Complex类对象转换成double类型数据)。在C++提供类型转换函数(type conversion function)来解决这个问题。类型转换函数的作用是将一个类的对象转换成另一类型的数据。

类型转换函数的一般形式为:

?

1

2

3
operator 类型名( ){

实现转换的语句

}

下面是简单实现。这时候,Base起了两方面的作用:类和数据类型。系统会在需要的时候自动调用对应的类方法。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32
#include <iostream>

using namespace std;

class Base{

private:

float x;

int y;

public:

Base (float xx=0,int yy=0){

x = xx;

y = yy;

}

operator float (){

return x;

}

operator int (){

return y;

}

void display(){

cout<<"x is :"<<x<<";y is :"<<y<<endl;

}

};

int main()

{

Base base(1.0,2);

base.display();

int y= base;

float x= base;

cout<<"NewX is :"<<x<<"NewY is:"<<y<<endl;

return 0;

}

基本运算符重载(自增自减)

主要总结 自增自减的前置和后置的用法。其他的加减乘除较简单。

简单的代码实现(纯语法)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57
#include <iostream>

using namespace std;

class Base{

private:

float x;

int y;

public:

Base (float xx=0,int yy=0){

x = xx;

y = yy;

}

operator float (){

return x;

}

operator int (){

return y;

}

Base operator ++(){//前置 ++

x++;

y++;

return *this;

}

Base operator --(){

x--;

y--;

return *this;

}

Base operator ++(int ){//后置 ++

Base temp = *this;

++(*this);

return temp;

}

Base operator --(int ){

Base temp = *this;

--(*this);

return temp;

}

void display(){

cout<<"x is :"<<x<<";y is :"<<y<<endl;

}

};

int main()

{

Base base(1.0,1);

Base tem = base++;

base.display();

tem.display();

Base base2(1.0,1);

tem = ++base2;

base.display();

tem.display();

return 0;

}

发现:

后置和前置的区别是有无int参数。

后置需要申请新的空间,大小是类的大小。所以,后置操作会有额外的时间空间开销。

尽量使用前置操作:如:for (int i=0;i<n;++i)

以上这篇浅谈C++类型转化(运算符重载函数)和基本运算符重载(自增自减)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持快网idc。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 浅谈C++类型转化(运算符重载函数)和基本运算符重载(自增自减) https://www.kuaiidc.com/74167.html

相关文章

发表评论
暂无评论