c++ - 在构造函数 C++ 中调用另一个对象的方法
问题描述
我试图从复制构造函数中调用 otherObjectArea 的 getter,并且我反驳了编译错误。我正在像 Java 一样做。我应该如何在 C++ 中正确地做到这一点?
class ObjectArea
{
private:
int x, y, width, height;
public:
ObjectArea(int x, int y, int width, int height)
{
this->x = x;
this->y = y;
this->width=width;
this->height = height;
}
ObjectArea():ObjectArea(0,0,0,0){}
ObjectArea(const ObjectArea &otherObjectArea){
this->x = otherObjectArea.getX();
this->y = otherObjectArea.getY();
this->width = otherObjectArea.getWidth();
this->height = otherObjectArea.getHeight();
}
int getX(){
return this->x;
}
int getY(){
return this->y;
}
int getWidth(){
return this->width;
}
int getHeight(){
return this->height;
}
};
编译错误:
ObjectArea.cpp:19:40: error: passing ‘const ObjectArea’ as ‘this’ argument discards qualifiers [-fpermissive]
19 | this->x = otherObjectArea.getX();
|
^
ObjectArea.cpp:25:9: note: in call to ‘int ObjectArea::getX()’
25 | int getX(){
| ^~~~
非常感谢。
解决方案
您正在调用引用,即getX
对const ObjectArea&
不得修改的对象的引用。但是,getX
没有标记为const
,即,您不保证该方法不会修改调用它的对象。
通过将其更改为:
int getX() const {
return this->x;
}
您将能够调用getX
参考const
。所有其他方法相同。
推荐阅读
- linux - 提取文本之间
- pine-script - 在结束交易前至少等待 n 秒?
- python - Python Networkx add_weighted_edges_from ValueError 3 列
- python - 用python3更改jpg图像的元数据和版权
- javascript - 如何使用 JS 和 p5.js 使类中的对象物理移动
- javascript - 使用捆绑包的 ASP.NET MVC 4 WebApp
- docker - Nginx 和 Docker - 如何转发到内部地址?
- php - 如何使用 livewire 而不是 ajax 加载数据?
- reactjs - react-simple-maps 中的可选状态
- php - 如何解决 livewire 中的图像预览问题