我有一个 Sphere 类,它继承了一个 Point 对象作为中心。当我通过 Sphere 构造函数创建一个 Sphere 对象时,它总是将中心初始化为 0,0,0,但它会正确设置半径。
访问 Sphere 的 setCenter() 方法也没有影响。我可以有效地改变球体中心点的 X、Y、Z 坐标的唯一方法是调用 Point 的 setX() 等方法。
如果这是一个明显的答案,我深表歉意,但我是 C++ 新手,正在为过渡而苦苦挣扎。如果我遗漏了任何重要信息,请随时告诉我。以下是相关代码:
主要的
#include <iostream>
#include <fstream>
#include "MovingSphere.h"
using namespace std;
int main() {
ifstream inFile("sphere.txt");
int X, Y, Z, R, DX, DY, DZ;
if (inFile) {
inFile >> X >> Y >> Z >> R
>> DX >> DY >> DZ;
}
else {
cerr << "\neRR: Cannot find input file.\n\n";
}
// create a sphere
Sphere sphereInstance(X, Y, Z, R);
sphereInstance.setCenter(1, 2, 3);
sphereInstance.setX(3);
cout << endl <<
"X = " << sphereInstance.getX() << endl <<
"Y = " << sphereInstance.getY() << endl <<
"Z = " << sphereInstance.getZ() << endl;
return 0;
}
点.cpp
#include "Point.h"
Point::Point() : x(0), y(0), z(0) { // default constructor (point at 0,0,0)
}
Point::Point(int X, int Y) : x(), y(), z(0) { // constructor for 2d point
}
Point::Point(int X, int Y, int Z) : x(), y(), z() { // constructor for 3d point
}
// set the points X coordinate (mutator)
void Point::setX(int newX) {
x = newX;
}
... etc.
点.h
#ifndef POINT_H
#define POINT_H
class Point {
public:
Point (); // default constructor (0,0,0);
Point(int X, int Y); // constructor for 2d point
Point(int X, int Y, int Z); // constructor for 3d point
void setX(int newX); // declaration
int getX() const; // declaration
etc...
private:
int x, y, z; // coordinates of point
};
#endif /* POINT_H */
球体.cpp
#define _USE_MATH_DEFINES
#include <math.h>
#include "Sphere.h"
Sphere::Sphere() :
center(), radius(0) {// default constructor (a point at 0,0,0)
}
Sphere::Sphere(int X, int Y, int Z, int R) { // sphere constructor
center = Point(X, Y, Z);
radius = R;
}
// set the sphere's center (mutator)
void Sphere::setCenter(int X, int Y, int Z) {
center.setX(X);
center.setY(Y);
center.setZ(Z);
}
... etc.
球体.h
#ifndef SPHERE_H
#define SPHERE_H
#include "Point.h"
class Sphere: public Point {
public:
Sphere(); // default constructor (a point at 0,0,0)
Sphere (int X, int Y, int Z, int R); // sphere constructor
void setRadius(int newRadius); // declaration
void setCenter(int X, int Y, int Z); // declaration
int getRadius() const; // declaration
private:
Point center; // center of sphere
int radius; // radius of sphere
};
#endif /* SPHERE_H */
输出
X = 3
Y = 0
Z = 0