在c ++中正确重载+

0 c++ operators

我创建了一个代表线的类,aX + bY = c 我希望重载+操作符更高的线(返回更高的线,所以我在下面做了,但编译器说invalid use of this

class Linia{
public:
    double a,b,c;
    Linia (double a, double b, double c){
        this->a = a;
        this->b = b;
        this->c = c;
    }
   friend Linia operator+ (double i){
   return new Linia(a, this->b, this->c + i/this->b);
}
};
Run Code Online (Sandbox Code Playgroud)

我想回新的Linia对象,它是具有如上所示像场iint我不希望修改原始对象

Mat*_*ine 5

您有一些基本的语法问题.

  • this是一个指针,因此您需要使用->它来取消引用它.

  • 我认为你的意思是this->c + i.c代替this->c + i

  • 您不需要(也可能不应该)让运营商成为朋友.

  • 返回新实例(如operator+)的运算符应按值返回,而不是在堆上分配.

  • 运营商普遍采取的参数作为const参考(因为你不应该改变操作数).

我想你的意思是这样的:

class Linia{
public:
    double a,b,c;
    Linia (double a, double b, double c){
        this->a = a;
        this->b = b;
        this->c = c;
    }
    Linia operator+ (const Linia& i){
        return Linia(this->a, this->b, this->c + i.c / this->b);
    }
};
Run Code Online (Sandbox Code Playgroud)

你可以清理这样的东西:

class Linia{
public:
    double a,b,c;
    Linia (double a, double b, double c)
        : a(a), b(b), c(c)
    { }

    Linia operator+ (const Linia& i){
        return Linia(a, b, c + i.c / b);
    }
};
Run Code Online (Sandbox Code Playgroud)