用转换构造函数可以将一个指定类型的数据转换为类的对象。但是不能反过来将一个类的对象转换为一个其他类型的数据(例如将一个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。
相关文章
猜你喜欢
- ASP.NET自助建站系统中的用户注册和登录功能定制方法 2025-06-10
- ASP.NET自助建站系统的域名绑定与解析教程 2025-06-10
- 个人服务器网站搭建:如何选择合适的服务器提供商? 2025-06-10
- ASP.NET自助建站系统中如何实现多语言支持? 2025-06-10
- 64M VPS建站:如何选择最适合的网站建设平台? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-25 17
-
2025-05-25 62
-
2025-05-29 56
-
2025-05-26 76
-
2025-05-29 33
热门评论

