【问题标题】:Accessing private variables of an object访问对象的私有变量
【发布时间】:2019-06-25 14:29:01
【问题描述】:

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

【问题讨论】:

  • 任何具体错误?分享实际的错误消息是传统的做法,因此我们不必猜测。
  • Point3D::calculateDistancePoint3D成员 函数。这意味着它可以访问该类的所有成员。否则,private 成员将无法使用——任何东西都无法访问它们,甚至类本身也无法访问!我建议获取a good C++ book 并从中学习。
  • "我用指针试过了,我用 &c 试过" ... &amp;c 指针。
  • 不要被&amp; 的含义所迷惑。 Point3D &amp; 声明一个引用,而在 &amp;c&amp; 是地址运算符,即使它们使用相同的符号,这两者也是不同的东西

标签: c++ class object pointers


【解决方案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-&gt;
  • 将您多次使用的表达式存储在一个变量中。

【讨论】:

    猜你喜欢
    • 2012-03-02
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-25
    • 2012-05-09
    • 2018-11-02
    • 1970-01-01
    相关资源
    最近更新 更多