在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
- 在c++中const引用引发的几个小问题
- 在毕设过程中遇到的几个小问题
- 在C编程中使用到的几个重要关键字之一const
- 在C编程中使用到的几个重要关键字之一const
- 一个引用 引发的问题
- 由引用引发的问题
- 碰见C语言的几个小问题
- 几个小例子引发的思考
- c#几个小例子引发的思考
- 由const引发的版本控制问题
- Spring中Bean的property,ref引发的小问题
- setInterval引发的小问题
- 开发中碰到的几个小问题
- linux中权限的几个小问题
- C/C++中const的问题
- 解决系统迁移到windows 2003 64位服务器后引发的几个小问题
- 在论坛中找到的几个关于Python的小问题的解决方法
- 在IE7 中遇到的几个小问题,有解决方案(转)
- 第13条:使类和成员的可访问性最小化
- 友盟统计
- 杭电1325 Is it A tree?(并查集)
- dsjob jobstatus 简述
- 黑马程序员_java 7k_银行调度业务系统
- 在c++中const引用引发的几个小问题
- vs2010 fftw安装使用
- Android中加入悬浮窗
- HDU 1195 Open the Lock (双向BFS)
- Head First设计模式C++实现--第五章:单件(Singleton)模式
- 创建对象(反射)
- 挖地雷
- MFC 多线程获取窗口
- iphone开源项目list