一个VC编译错误引发的对显示类型转换的思考(static_cast、dynamic_cast和const_cast)(二)
point p(1, 2);
point p1(p); //initialize p1 with p
point p2 = point::reverse(p1);
p2.print();
return 0;
}
bingo,编译通过!
按照plan B的修改:
[cpp]
#include
using namespace std;
class point
{
private:
int m_x,m_y;
public:
point()
{
m_x = 0;
m_y = 0;
}
point(int x, int y)
{
m_x = x;
m_y = y;
}
point(const point& p)
{
m_x = p.m_x;
m_y = p.m_y;
cout<<"copy constructor is called!"<
}
static point reverse(const point& p)
{
point p1;
p1.m_x = static_cast(p).getY(); //将const point类型显示转换为point类型
p1.m_y = static_cast(p).getX(); //将const point类型显示转换为point类型
return p1;
}
int getX()
{
return m_x;
}
int getY()
{
return m_y;
}
void print()
{
cout<
}
};
int main()
{
point p(1, 2);
point p1(p); //initialize p1 with p
point p2 = point::reverse(p1);
p2.print();
return 0;
}
同样编译通过了!
对于plan B,同样可以采用const_cast进行类型转换:
[cpp]
// CastExample.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include
using namespace std;
class point
{
private:
int m_x,m_y;
public:
point()
{
m_x = 0;
m_y = 0;
}
point(int x, int y)
{
m_x = x;
m_y = y;
}
point(const point& p)
{
m_x = p.m_x;
m_y = p.m_y;
cout<<"copy constructor is called!"<
}
static point reverse(const point& p)
{
point p1;
p1.m_x = const_cast(p).getY(); //将const point类型显示转换为point类型
p1.m_y = const_cast(p).getX(); //将const point类型显示转换为point类型
return p1;
}
int getX()
{
return m_x;
}
int getY()
{
return m_y;
}
void print()
{
cout<
}
};
int main()
{
point p(1, 2);
point p1(p); //initialize p1 with p
point p2 = point::reverse(p1);
p2.print();
return 0;
}
注意:在使用const_cast进行转换的时候,尖括号中的参数必须是引用类型,即:const_cast(p).getY()
四、进一步探讨(关于C++类型转换)
C++类型转换分为:隐式类型转换和显式类型转换
1.隐式类型转换
又称为“标准转换”或者“自动类型转换”,由编译
系统自动完成,对程序员透明。包括以下几种情况:
1) 算术转换(Arithmetic conversion) : 在混合类型的算术表达式中, 最宽的数据类型成为目标转换类型。
int ival = 3;
double dval = 3.14159;
ival + dval;//ival被提升为double类型,结果是个double类型
2)一种类型表达式赋值给另一种类型的对象:目标类型是被赋值对象的类型
int *pi = 0; // 0被转化为int *类型
ival = dval; // double->int
例外:void指针赋值给其他指定类型指针时,不存在标准转换,编译出错
3)将一个表达式作为实参传递给函数调用,此时形参和实参类型不一致:目标转换类型为形参的类型
extern double sqrt(double);
cout << "The square root of 2 is " << sqrt(2) << endl;//2被提升为double类型:2.0
4)从一个函数返回一个表达式,表达式类型与返回类型不一致:目标转换类型为函数的返回类型
double difference(int ival1, int ival2)
{
return ival1 - ival2; //返回值被提升为double类型
}
2.显式类型转换
又称“强制类型转换”(cast),由程序员完成。
C++标准定义了四个类型转换符:reinterpret_cast, static_cast, dynamic_cast 和 const_cast,目的在于控制类(class)之间的类型转换。
(1)static_cast
用法:static_cast ( expression )
说明:该运算符把expressio