10

Having difficulty declaring an overloaded operator in the c ++ header file

 2 years ago
source link: https://www.codesd.com/item/having-difficulty-declaring-an-overloaded-operator-in-the-c-header-file.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Having difficulty declaring an overloaded operator in the c ++ header file

advertisements

So I am making a program that will do some operations with polynomials and I am using a vector full of a struct I defined to represent a polynomial. Part of what I am trying to do is to overload the +,-,*.+=,-= and *= operators.

term is a struct I defined.

I am trying to contain all of the overload methods within a class.

I have a single file that overloads it and works fine. The method is defined as:

vector<term> operator+(vector<term> t1, vector<term> t2)

When I try and put that in a c++ header file to use it in a class I get this error:

Method declaration in header:

vector<term> operator+(vector<term> v1,vector<term> v2);

Error I get:

poly.h:25:71: error: ‘std::vector<term> Polynomial::operator+(std::vector<term>, std::vector<term>)’ must take either zero or one argument
     vector<term> operator+(const vector<term> v1,const vector<term> v2);

Why would it work in one instance and not the other?

I am new to c++ so forgive if I miss any blatant mistakes.


From the error message:

std::vector Polynomial::operator+(std::vector, std::vector) [...]

I deduce that you declared operator +() as a member of class Polynomial. As a member of this class, it must take either zero or one argument (as the message says).

The overload taking zero argument is called when evaluating the expression +p for some p of type Polynomial. The overload taking one argument of type say, std::vector<term>, is used when evaluating the expression p + q where p has type Polynomial and q has type std::vector<term> (or anything implicitly convertible to it).

It looks like that you need this function

vector<term> operator+(vector<term> v1,vector<term> v2);

to be declared and defined outside any class. It might be either in the global namespace (not advisable) or inside the namespace containing term (preferable).

In addition, I would expect the correct declaration to be

vector<term> operator+(const vector<term>& v1, const vector<term>& v2);

since inside this function you (probably) don't need to make a copy of either operand to work on and you just need reading access to them.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK