C++ 我应该如何声明此运算符重载?

C++ 我应该如何声明此运算符重载?,c++,C++,我需要将常量向量乘以int,但我必须将重载声明为非成员函数,而不是方法,否则它将无法编译;如何将重载作为方法写入 namespace N { class Vector { public: double x, y, z; Vector( ); Vector(double x, double y = 0, double z = 0); Vector operator*(double k); //fri

我需要将
常量向量
乘以
int
,但我必须将重载声明为非成员函数,而不是方法,否则它将无法编译;如何将重载作为方法写入

namespace N
{
    class Vector {
    public:
        double x, y, z;

        Vector( );
        Vector(double x, double y = 0, double z = 0);

        Vector operator*(double k);
        //friend Vector operator*(const Vector u, double k);
    };
}

namespace N
{
    Vector::Vector( )
    {
        x = 0;
        y = 0;
        z = 0;
    }

    // Creates a vector with initial Cartesian components.
    //
    Vector::Vector(double x, double y, double z) :
        x(x),
        y(y),
        z(z)
    {
    }

    // Allows multiplying a vector by a scalar.
    //
    Vector Vector::operator*(double k)
    {
        Vector scaled;
        scaled.x = x * k;
        scaled.y = y * k;
        scaled.z = z * k;
        return scaled;
    }

    // Allows multiplying a vector by a scalar.
    //
    /*Vector operator*(const Vector u, double k)
    {
        return Vector(u.x * k, u.y * k, u.z * k);
    }*/
}



const N::Vector A(3, 4);
const N::Vector B(4, 3);

int main( )
{
    N::Vector resulting = A * 3;
    return 0;
}

作为成员,只需将代码更改为

 Vector operator*(double k) const;
在定义中

 Vector Vector::operator*(double k) const ...
作为顶级:

friend Vector operator*(const Vector& u, double k);


作为成员,只需将代码更改为

 Vector operator*(double k) const;
在定义中

 Vector Vector::operator*(double k) const ...
作为顶级:

friend Vector operator*(const Vector& u, double k);


必须将其声明为
const
方法。最好使用非成员运算符使乘法可交换。必须将其声明为
const
方法。最好使用非成员运算符使乘法可交换。