Re: == operation on vectors
subramanian100in@yahoo.com, India wrote:
In the following program, I have used operator==() as member function
for learning purpose only.
consider the following program:
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
class Test
{
public:
Test(int arg);
Test(const Test &rhs);
Test& operator=(const Test &rhs);
inline int value() const;
inline bool operator==(const Test &rhs) const;
'inline' means nothing if you don't supply the definition right after
the declaration. Besides, 'inline' is *implicit* if you *define* the
functions in the class definition. So you can safely remove the
'inline' from the two declarations above.
private:
int val;
};
Test::Test(int arg) : val(arg)
{
}
Test::Test(const Test &rhs) : val(rhs.val)
{
}
Test &Test::operator=(const Test &rhs)
{
if (this != &rhs)
val = rhs.val;
return *this;
}
inline int Test::value() const
{
return val;
}
inline bool Test::operator==(const Test &rhs) const
{
return value() == rhs.value();
}
int main()
{
vector<Test> c1;
c1.push_back(Test(10));
vector<Test> c2;
c2.push_back(Test(10));
if (c1 == c2)
cout << "c1 equals c2" << endl;
else
cout << "not equal" << endl;
return EXIT_SUCCESS;
}
I compiled this program with g++ -std=c++98 -pedantic -Wall -Wextra.
It produced the output
c1 equals c2
However if I remove 'const' from the comparison member function
bool Test::operator==(const Test &rhs) const
ie if I have
bool Test::operator==(const Test &rhs)
Then I get compilation error for the line
if (c1 == c2)
It might be useful if you actually posted what error you get...
What is the reason for the compilation error when Test::operator==()
is made non-const ?
It's quite possible that the operator== for vectors is defined to accept
two arguments, and both of them 'const'. The function then probably
attempts to do comparison of the sizes and then if they are the same,
the element-wise comparison of the storage. In a const vector the
storage is also most likely const. So, it looks for a function that
compares the stored types and both values are 'const'. If your
'Test::op==' needs a non-const lhs argument, the language cannot convert
the const reference it obtains from a const vector to a reference to
non-const object, so it complains.
If I remove operation==() from Test class and make it a free function,
then also the compilation error is gone and the program works fine as
it should be.
And define it how? Both arguments 'const'? Try removing const from one
of them or from both.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask