【发布时间】: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::calculateDistance是Point3D的成员 函数。这意味着它可以访问该类的所有成员。否则,private成员将无法使用——任何东西都无法访问它们,甚至类本身也无法访问!我建议获取a good C++ book 并从中学习。 -
"我用指针试过了,我用 &c 试过" ...
&c是指针。 -
不要被
&的含义所迷惑。Point3D &声明一个引用,而在&c中&是地址运算符,即使它们使用相同的符号,这两者也是不同的东西