Search code examples
c#operator-overloadingoperator-keyword

Operator overloading changes operands


This is my try to explain my previous question more, since the previous one didn't get the answers I need.

Suppose I have two classes, the first class is a Symbol, it has a char, (double)coefficient, and (double)power. Overloading the minus operator is in this way:

public static Symbol operator -(Symbol symbol)
    => new(symbol.symbol, -symbol.Coefficient, symbol.Exponent);

And I have the following code:

Symbol sym = new('x', 3, 1);
Console.WriteLine(-sym); // output: -3*x
Console.WriteLine(sym);  // output: 3*x

At this point, it all makes sense, but when I have the second class, Polynomial, that is a list of symbols, and I have the following minus overloading function:

public static Polynomial operator -(Polynomial polynomial)
{

    Polynomial result = polynomial;

    for (int i = 0; i < result.container.Count; i++)
        result.container[i] = -result.container[i];

    return result;
}

The container[i] here is a Symbol object.

When I execute the following:

Console.WriteLine(polynomial); // output: 3*x + 2*y
Console.WriteLine(-polynomial); // output: -3*x - 2*y
Console.WriteLine(polynomial); // output: -3*x - 2*y

Whereas the last expected output should be '3x + 2y'

So what I should do to solve this problem?


Solution

  • You should create a new instance of Polynomial just like what you did in the Symbol class.

    public static Polynomial operator -(Polynomial polynomial)
    {
        Polynomial result = new Polynomial { container = new List<Symbol>() };
    
        for (int i = 0; i < polynomial.container.Count; i++)
            result.container.Add(-polynomial.container[i]);
    
        return result;
    }