简体   繁体   中英

Accessing private variables of an object

I don't know if my function{{ Point3D::calculateDistance(Point3D &p) }} is written right. How do I access the variables of the Point3D object p?

If that part is right how do I call this function in my main?

For the second part of my question I have tried with a pointer and I have tried with &c where c is a Point3D object but neither seems to work.

#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; }

The only compiler error appears to happen when I call the calculateDistance function.

Your function is declared like this:

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

So it takes a reference. However, you invoke it with a pointer (address of object c ):

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

Make sure to invoke it directly on the object (which is then bound to a reference):

b.calculateDistance(c);

Furthermore, some tips:

  • Use const wherever no modification is done. This concerns both the member function and its parameter.
  • Consider naming parameters differently than member variables, so you don't need this-> .
  • Store expressions that you use multiple times in a variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM