访问对象的私有变量

时间:2019-06-25 14:29:01

标签: c++ class object pointers

我不知道我的函数{{Point3D :: calculateDistance(Point3D&p)}}是否正确编写。如何访问Point3D对象p的变量?

如果该部分是正确的,我该如何在我的主体中调用此函数?

对于我的问题的第二部分,我尝试使用一个指针,而我尝试使用&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函数时,唯一的编译器错误似乎发生了。

1 个答案:

答案 0 :(得分:1)

您的函数声明如下:

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

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

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

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

b.calculateDistance(c);

此外,一些技巧:

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