<<只能使用友元函數的形式重載,+運算符可以友元也可以成員函數方式重載,但是參數的個數就不同了。以友元函數方式重載+運算符是兩個參數,以成員函數重載只有一個參數。
point.h:
#include <iostream>
using namespace std;
class Point
{
public:
Point();
Point(int x, int y);
Point(const Point& p);
friend ostream & operator<<(ostream &out, Point &p);
Point operator+(Point& p);
~Point();
int getX();
int getY();
private:
int m_x;
int m_y;
};
point.cpp:
#include <iostream>
#include "point.h"
using namespace std;
Point::Point(): m_x(0), m_y(0)
{
}
Point::Point(int x, int y): m_x(x), m_y(y)
{
}
Point::~Point()
{
}
int Point::getX()
{
return this->m_x;
}
int Point::getY()
{
return this->m_y;
}
ostream & operator<<(ostream &out, Point &p)
{
out << '[' << p.m_x << ", " << p.m_y << ']';
return out;
}
Point Point::operator+(Point& p)
{
int x = this->m_x + p.m_x;
int y = this->m_y + p.m_y;
Point newp = Point(x, y);
return newp;
}
g++ -c -fPIC point.h -o point.o
編譯成.o文件。
g++ -shared point.o -o point.so
#include <iostream>
#include "point.h"
using namespace std;
int main()
{
Point p1 = Point(1, 1);
Point p2 = Point(1, 2);
Point p3 = p1 + p2;
cout << p3 << endl;
return 0;
}
最後使用動態庫:
g++ main.cpp -o main -L. -lpoint
打印結果:
[2, 3]