C++ 访问对象的私有变量

C++ 访问对象的私有变量,c++,class,object,pointers,C++,Class,Object,Pointers,我不知道我的函数{{Point3D::CalculateInstancePoint3D&p}}是否写对了。如何访问Point3D对象p的变量 如果那部分是正确的,我如何在main中调用这个函数 对于问题的第二部分,我试过使用指针,也试过使用&c,其中c是Point3D对象,但两者似乎都不起作用 #include <iostream> #include <string> #include <cmath> using namespace std; class

我不知道我的函数{{Point3D::CalculateInstancePoint3D&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; }

调用CalculateInstance函数时,出现唯一的编译器错误。

您的函数声明如下:

float Point3D::calculateDistance(Point3D &p) { ... }
所以它需要一个参考。但是,您可以使用对象c的指针地址调用它:

确保直接在绑定到引用的对象上调用它:

b.calculateDistance(c);
此外,还有一些提示:

在没有修改的地方使用const。这涉及到成员函数及其参数。 考虑与成员变量不同地命名参数,因此您不需要这个->。 在变量中存储多次使用的表达式。
有什么具体的错误吗?传统的做法是共享实际的错误消息,因此我们不必猜测。Point3D::CalculateInstance是Point3D的一个成员函数。这意味着它可以访问该类的所有成员。否则,私有成员将无法使用-任何东西都无法访问它们,甚至类本身也无法访问!我建议从中学习。我试过使用指针,也试过使用&c&c是一个指针。不要被不同的含义所迷惑。Point3D&声明一个引用,而在&c中,&是运算符的地址,这两个是不同的东西,即使它们使用相同的符号
b.calculateDistance(c);