一个VC编译错误引发的对显示类型转换的思考(static_cast、dynamic_cast和const_cast)(一)

2014-11-24 02:21:07 · 作者: · 浏览: 10
一、问题提出
今天在研究effective c++中碰到的copy构造函数的时候,运行了下面这个程序,编译出现了错误:
[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 = p.getY();
p1.m_y = p.getX();
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;
}
错误信息为:
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Compiling...
item3.cpp
D:\Project\EffctiveCProj1\item3.cpp(32) : error C2662: 'getY' : cannot convert 'this' pointer from 'const class point' to 'class point &'
Conversion loses qualifiers
D:\Project\EffctiveCProj1\item3.cpp(33) : error C2662: 'getX' : cannot convert 'this' pointer from 'const class point' to 'class point &'
Conversion loses qualifiers
Error executing cl.exe.
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
二、问题分析
分析了一下错误提示,发现是不能将类型从const class point转为class point &,定位到代码,原来出现在line21和line22 getY()和getX()调用这里:
p1.m_x = p.getY();
p1.m_y = p.getX();
p是一个const point&类型,而getY()和getX()都是非const类型,按照C++的规定,const常量无法调用非const函数,只可以调用const函数,因为const常量对象的数据成员是不允许改变的,非const函数就有可能改变数据成员,因此不允许调用!
三、问题解决
既然明白了这点,就很好修改了,两种方式:
A、将getX()和getY()改成const函数(简单)
const函数只需要在函数定义的地方的参数列表之后花括号之前加上const即可
B、将p转换为非const变量(稍微复杂)
在《effective c++》的“item 03:尽可能的使用const”一章中,作者介绍了如何将const类型转换为非const类型,即:采用static_cast或者const_cast.
按照plan A的修改:
[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 = p.getY();
p1.m_y = p.getX();
return p1;
}
int getX() const //const函数
{
return m_x;
}
int getY() const //const函数
{
return m_y;
}
void print()
{
cout<
}
};
int main()
{