This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Why can not use reference in operator function?
- From: Parmenides <mobile dot parmenides at gmail dot com>
- To: gcc-help at gcc dot gnu dot org
- Date: Sun, 24 Nov 2013 00:54:04 +0800
- Subject: Why can not use reference in operator function?
- Authentication-results: sourceware.org; auth=none
Hi,
I have the following code:
#include <iostream>
#include <cstring>
using namespace std;
class Int{
int x;
public:
Int(int i = 0)
{
x = i;
}
~Int()
{
}
void show()
{
cout << x << endl;
}
friend Int operator+(Int &a, Int &b) // Because 'b' is a reference to
object rather than an object
{
return Int(a.x+b.x);
}
};
int main()
{
Int i(3), j;
j = i + Int(6); // This can not call constructor.
j.show();
return 0;
}
Gcc issues error message, but VC++ 2010 compile it successfully. I
tried to modify
friend Int operator+(Int &a, Int &b)
to
friend Int operator+(Int a, Int b)
both compiler can get it pass. Why Gcc does not want to convert a
'int' to a 'Int' object in the '+' operator function when its second
parameter is a reference to object rather than an objetc?
I further modified
j = i + Int(6);
to
j = i + 6;
both compiler can get it pass again. Therefore, I think it seem that
Gcc encourage programmers to use implict conversion like 'i + 6'
rather that explict conversion like 'i + Int(6)'. Is this right? If
so, does this practice comfore to the C++ standard?