首页 > 解决方案 > 访问对象的私有变量

问题描述

我不知道我的函数{{ 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 函数时,似乎发生了唯一的编译器错误。

标签: c++classobjectpointers

解决方案


您的函数声明如下:

float Point3D::calculateDistance(Point3D &p) { ... }

所以需要参考。但是,您使用指针(对象的地址c)调用它:

Point3D b(3,4,0);
Point3D c(0,0,0);
b.calculateDistance(&c);

确保直接在对象上调用它(然后绑定到引用):

b.calculateDistance(c);

此外,一些提示:

  • const在没有修改的地方使用。这涉及成员函数及其参数。
  • 考虑以不同于成员变量的方式命名参数,因此您不需要this->.
  • 将您多次使用的表达式存储在一个变量中。

推荐阅读