我必须实例化这个类吗?或者这是一个错误的责任分离?

Jos*_*pez 3 c++ oop

我正在练习课程,我创建了一个程序来创建一个矢量并计算它的大小.我将代码分开,以便一个类是一个矢量类,另一个类处理数学.我的问题是,这是不正确的?我必须实例化我的数学课才能够使用它,它看起来很笨,即使它有效.

主要:

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;
}
Run Code Online (Sandbox Code Playgroud)

矢量类:

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


};
Run Code Online (Sandbox Code Playgroud)

数学课:

class Math {
    public:
        double magnitude(const Vector3D* v);
};
Run Code Online (Sandbox Code Playgroud)

Don*_*eba 8

类用于封装状态.Math没有状态,因此它应该是命名空间,而不是类.


R S*_*ahu 6

我的问题是,这是不正确的?

根据Scott Meyers的说法,非成员函数改进了封装.

如果您可以使用非成员函数来实现函数,那么最好这样做.

使用另一个类的成员函数来进行计算是没有意义的.最好使用a namespace并在中定义函数namespace.