C++在类之间调用static_cast转换时,需要复制构造函数

本文探讨了C++中不同类之间的类型转换问题,包括编译错误的原因及如何通过正确的构造函数实现类型转换。文章通过具体示例展示了直接赋值与reinterpret_cast的不当使用及其引发的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面代码因为T2没有实现T2(T1)复制构造函数,所以编译错误

g++报错:test.cpp|23 col 25| 错误: 对‘T2::T2(T1&)’的调用没有匹配的函数

#include <vector>
#include<stdio.h>
#include <string.h>
#include<iostream>
#include <string>
using namespace std;
class T1{
	public:
	int a;
	double b;
};
class T2{
	public:
	int a;
	double b;
};
int main()
{
	T1 t1;
	t1.a = 2, t1.b = 1.5;
	T2 t2 = static_cast<T2>(t1);
	return 0;
}

类之间不能用reinterpret_cast转换,尽管定义了T2(T1&)也出错:

G++报错:test.cpp|27 col 33| 错误: 从类型‘T1’到类型‘T2’的转换无效

#include <vector>
#include<stdio.h>
#include <string.h>
#include<iostream>
#include <string>
using namespace std;
class T1{
	public:
	int a;
	double b;
};
class T2{
	public:
		T2(T1& t1)
		{
			a = t1.a;
			b = t1.b;
		}
	int a;
	double b;
};
int main()
{
	T1 t1;
	t1.a = 2, t1.b = 1.5;
	T2 t2 = reinterpret_cast<T2>(t1);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值