我正在练习班,我创建了一个程序,创建一个向量并计算它的大小。我将代码分开,以便一个类是矢量类,另一个类处理数学。我的问题是,这是不正确的?为了能够使用它,我必须实例化我的数学类,并且它看起来很笨重,尽管它很有用。我必须实例化这个类吗?或者这是责任分离的错误?
主营:
int main()
{
// Instantiate math library... ?
Math math; // <-- Instantiating math library here
Vector3D *test = new Vector3D("Test vector 1", 0, 0, 1);
printVector(test);
// Calling math library to calculate magnitude
std::cout << "Test vector 1 magnitude: " << math.magnitude(test) << std::endl;
return 0;
}
Vector类:
class Vector3D {
private:
std::string name;
double x;
double y;
double z;
public:
Vector3D();
Vector3D(std::string, double, double, double);
// Setters
void setName(std::string);
void setX(double);
void setY(double);
void setZ(double);
// Getters
std::string getName() const;
double getX() const;
double getY() const;
double getZ() const;
// Operators
Vector3D& operator *=(double s); // Scalar multiplication
Vector3D& operator /=(double s); // Scalar division
};
数学类:
class Math {
public:
double magnitude(const Vector3D* v);
};
这并没有错,但面向对象编程背后的想法之一是将代码与它将操作的数据打包在一起。鉴于此,我认为将magnitude()作为Vector3D类的成员函数比保持它的独立性会更有用。 –
太宽了。也许http://codereview.stackexchange.com/会更适合这个问题。 –