P
PengYu.UT
Hi,
I have the following two programs. One is to overload += as a free
function, the other is to overload += as a member function. Both of
them works fine.
I'm wondering which one I should choose in practice. What are the pros
and cons for these two implementations?
Thanks,
Peng
$ cat main_free.cc
#include <iostream>
class Integer {
public:
Integer(int i) : _i(i) {}
friend Integer &operator+=(Integer &, int);
friend std:stream &operator<<(std:stream &, const Integer &);
private:
int _i;
};
Integer & operator+=(Integer & I, int i) {
I._i += i;
return I;
}
std:stream &operator<<(std:stream &os, const Integer &I) {
os << "Integer: " << I._i;
return os;
}
int main ()
{
Integer I(0);
std::cout << I << std::endl;
I += 10;
std::cout << I << std::endl;
}
$ cat main_member.cc
#include <iostream>
class Integer {
public:
Integer(int i) : _i(i) {}
Integer &operator+=(int i) {
_i += i;
return *this;
}
friend std:stream &operator<<(std:stream &, const Integer &);
private:
int _i;
};
std:stream &operator<<(std:stream &os, const Integer &I) {
os << "Integer: " << I._i;
}
int main ()
{
Integer I(0);
std::cout << I << std::endl;
I += 10;
std::cout << I << std::endl;
}
$ ./main_free.exe
Integer: 0
Integer: 10
$ ./main_member.exe
Integer: 0
Integer: 10
I have the following two programs. One is to overload += as a free
function, the other is to overload += as a member function. Both of
them works fine.
I'm wondering which one I should choose in practice. What are the pros
and cons for these two implementations?
Thanks,
Peng
$ cat main_free.cc
#include <iostream>
class Integer {
public:
Integer(int i) : _i(i) {}
friend Integer &operator+=(Integer &, int);
friend std:stream &operator<<(std:stream &, const Integer &);
private:
int _i;
};
Integer & operator+=(Integer & I, int i) {
I._i += i;
return I;
}
std:stream &operator<<(std:stream &os, const Integer &I) {
os << "Integer: " << I._i;
return os;
}
int main ()
{
Integer I(0);
std::cout << I << std::endl;
I += 10;
std::cout << I << std::endl;
}
$ cat main_member.cc
#include <iostream>
class Integer {
public:
Integer(int i) : _i(i) {}
Integer &operator+=(int i) {
_i += i;
return *this;
}
friend std:stream &operator<<(std:stream &, const Integer &);
private:
int _i;
};
std:stream &operator<<(std:stream &os, const Integer &I) {
os << "Integer: " << I._i;
}
int main ()
{
Integer I(0);
std::cout << I << std::endl;
I += 10;
std::cout << I << std::endl;
}
$ ./main_free.exe
Integer: 0
Integer: 10
$ ./main_member.exe
Integer: 0
Integer: 10