在c++中const引用引发的几个小问题

来源:互联网 发布:java tcp协议开发 编辑:程序博客网 时间:2024/06/16 12:54

首先  遇到这个问题是在写一个类中函数的时候

原型如下

其中省略了部分代码

#include<iostream>
using namespace std;
class Point2D
{
public:
Point2D(float x = 0.0, float y = 0.0) :_x(x), _y(y){};
float x(){
return _x;
}
float y() {
return _y;
}


void x(float NewX){
_x = NewX;
}


void y(float NewY){
_y = NewY;
}




void operator+=(const Point2D& rhs){
_x +=rhs.x();
_y +=  rhs.y();

}


protected:
float _x, _y;
};


这个函数为什么会报错呢?

在vs2013中,经过编译,报的错误如下

error C2663: 'Point2D::y' : 2 overloads have no legal conversion for 'this' pointer


原因是什么呢?

const & 返回的也是一个const的变量 

所以解决方案如下


class Point2D
{
public:
Point2D(float x = 0.0, float y = 0.0) :_x(x), _y(y){};
float x(){
return _x;
}
float y() const{
return _y;
}


void x(float NewX){
_x = NewX;
}


void y(float NewY){
_y = NewY;
}




void operator+=(const Point2D& rhs){
Point2D pt = const_cast<Point2D&>(rhs);
_x += (pt.x() );
_y +=  rhs.y();

}


protected:
float _x, _y;
};


1.  让x()函数的返回值为const  就可以解决这个问题了。

2. 转型const_cast来解决这个问题

具体如下

void operator+=(const Point2D& rhs){
Point2D pt = const_cast<Point2D&>(rhs);
_x += (pt.x() );
_y +=  rhs.y();

}

将   const Point2D& 转化为 Piont2D& 即可



最后上源代码和运行结果

#include<iostream>
using namespace std;
class Point2D
{
public:
Point2D(float x = 0.0, float y = 0.0) :_x(x), _y(y){};
float x(){
return _x;
}
float y() const{
return _y;
}


void x(float NewX){
_x = NewX;
}


void y(float NewY){
_y = NewY;
}




void operator+=(const Point2D& rhs){
Point2D pt = const_cast<Point2D&>(rhs);
_x += (pt.x() );
_y +=  rhs.y();

}


protected:
float _x, _y;
};


class Point3D :public Point2D{
protected:
float _z;
public:
Point3D(float x = 0.0, float y = 0.0, float z = 0.0) :Point2D(x,y), _z(z){};

float z() const
{
return _z;
}


void z(float NewZ) {
_z = NewZ;
}


void operator+=(const Point3D& rhs)
{
Point2D::operator+=(rhs);
_z += rhs.z();
}


void Print()
{
cout << _x << _y << _z << endl;
}


};


int main()
{
Point3D p(1.0, 2.0, 3.0);
p.Print();


getchar();
getchar();


return 0;
}


运行结果为123



0 0
原创粉丝点击