c++ - 访问对象的私有变量
问题描述
我不知道我的函数{{ Point3D::calculateDistance(Point3D &p) }} 是否写对了。如何访问 Point3D 对象 p 的变量?
如果那部分是正确的,我该如何在我的 main 中调用这个函数?
对于我的问题的第二部分,我尝试使用指针,并且尝试使用 &c,其中 c 是 Point3D 对象,但似乎都不起作用。
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
class Point{
protected:
float x;
float y;
public:
Point(float x, float y);
float calculateDistance(float x, float y);
};
class Point3D : public Point{
float z;
public:
Point3D(float i, float j, float z);
float calculateDistance(float x, float y, float z);
float calculateDistance(Point3D &p);
};
Point::Point(float x, float y){
this->x = x;
this->y = y;
};
Point3D::Point3D(float x, float y, float z) : Point(x, y){
this->z = z;
};
float Point::calculateDistance(float x, float y){
float dist = sqrt(((this->x)-x)*((this->x)-x)+((this->y)-y)*((this->y)-y));
cout << dist << endl;
return dist;
}
float Point3D::calculateDistance(float x, float y, float z){
float dist = sqrt(((this->x)-x)*((this->x)-x)+((this->y)-y)*((this->y)-y)
+((this->z)-z)*((this->z)-z));
cout << dist << endl;
return dist;
}
//NOT SURE ABOUT THE FOLLOWING PART
//HOW DO I ACCESS THE X,Y,Z OF THE POINT3D OBJECT P??
float Point3D::calculateDistance(Point3D &p){
calculateDistance(p.x, p.y , p.z);
return 0;
}
int main(){
Point a(3,4);
a.calculateDistance(0,0);
Point3D b(3,4,0);
b.calculateDistance(0,0,0);
Point3D c(0,0,0);
//THE FOLLOWING IS THE ONLY COMPILER ERROR
//SETTING A POINTER TO THE OBJECT AND CALLING WITH THE POINTER AS ARGUMENT
//DOESNT SEEM TO WORK EITHER
b.calculateDistance(&c);
return 0; }
当我调用 calculateDistance 函数时,似乎发生了唯一的编译器错误。
解决方案
您的函数声明如下:
float Point3D::calculateDistance(Point3D &p) { ... }
所以需要参考。但是,您使用指针(对象的地址c
)调用它:
Point3D b(3,4,0);
Point3D c(0,0,0);
b.calculateDistance(&c);
确保直接在对象上调用它(然后绑定到引用):
b.calculateDistance(c);
此外,一些提示:
const
在没有修改的地方使用。这涉及成员函数及其参数。- 考虑以不同于成员变量的方式命名参数,因此您不需要
this->
. - 将您多次使用的表达式存储在一个变量中。
推荐阅读
- php - 在我的购物车列表中添加一个表格列而不是行
- java - 如何在 textView 中显示 JSON 凌空请求响应的对象(以 HTML 格式)形式?
- angular - 如何设置单独的开发和发布代理/后端 api url?
- android - 如果我在下载时重新启动活动,如何处理布局中的进度条和其他 UI 更新?
- angular - 断言变量已定义
- typo3 - TYPO3 TCA 类别和 FAL
- javascript - 模态关闭后停止 iframe 自动播放
- docker - 如何将文件复制到docker容器中的主机挂载目录
- ruby-on-rails - 安装gem“设计”时如何修复错误?
- excel - 如何在 COUNTIFS 中使用 OR 条件?