zoukankan      html  css  js  c++  java
  • C++在类之间调用static_cast转换时,需要复制构造函数

    下面代码因为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;
    }


  • 相关阅读:
    P1456 Monkey King
    P3377 【模板】左偏树(可并堆)
    P1074 靶形数独
    P1120 小木棍
    P5490 【模板】扫描线
    糖糖别胡说,我真的不是签到题目
    最长公共子序列
    最长上升子序列
    数的三次方根
    地、颜色、魔法(dfs)
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3052982.html
Copyright © 2011-2022 走看看