如何通过运算符重载解决此问题?

时间:2019-12-20 18:33:36

标签: c++ vector sum operator-overloading add

我正在尝试学习C ++,并且想解决这两个问题。

在此任务中,如何用operator +将两个向量求和? 如何与操作员一起制作标量产品* 我想在课外写他们

class Vector{
    double x;
    double y;

public:
    Vector() : x(0), y(0){};
    Vector(double x, double y);
    double getX() const;
    Vector operator+(Vector arg);
    Vector operator*(double len);

};


Vector::Vector(double x1=1, double y1=2)
:x(x1),y(y1){};


double Vector::getX() const {return x;}


1 个答案:

答案 0 :(得分:-1)

以下是实现该类并对其进行测试的代码 请注意,我添加了功能displayVector()来显示对象

    #include<iostream>

 class Vector{
    double x;
    double y;

public:
    Vector() : x(0), y(0){};
    Vector(double x, double y);
    double getX() const;
    double getY() const;
    friend Vector operator+(const Vector& arg1,const Vector& arg2);
    friend Vector operator*(const double& len,const Vector& arg);
    void displayVector()const;

};

double Vector::getX() const {return x;}
double Vector::getY() const {return y;}
void Vector::displayVector() const {
    std::cout<<"\nX compis: "<<x<<"\tY comp is: "<<y<<std::endl;
}


Vector::Vector(double x1=1, double y1=2):x(x1),y(y1){}

Vector operator+(const Vector& arg1, const Vector& arg2){

    return Vector(arg1.getX()+arg2.getX(),arg1.getY()+arg2.getY());
}

Vector operator*(const double& len, const Vector& arg){

    return Vector(len*arg.getX(),len*arg.getY());
}

int main(){

    Vector v1{1,2}, v2{2,3};
    v1.displayVector();
    v2.displayVector();
    (v1+v2).displayVector();
    (2*v1).displayVector();

    return 0;
}