以下是運算符重載的示例代碼。 什麼是「&」是指在語法「&」是什麼意思在運算符重載
complx operator+(const complx&) const; ?
#include <iostream>
using namespace std;
class complx
{
double real,
imag;
public:
complx(double real = 0., double imag = 0.); // constructor
complx operator+(const complx&) const; // operator+()
};
// define constructor
complx::complx(double r, double i)
{
real = r; imag = i;
}
// define overloaded + (plus) operator
complx complx::operator+ (const complx& c) const
{
complx result;
result.real = (this->real + c.real);
result.imag = (this->imag + c.imag);
return result;
}
int main()
{
complx x(4,4);
complx y(6,6);
complx z = x + y; // calls complx::operator+()
}
這是一個參考。任何[體面的入門C++書](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)應該涵蓋這一點。 – 2013-04-22 09:24:33
維基百科還爲初學者提供了不錯的信息:[運營商wiki](http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Member_and_pointer_operators) – Dariusz 2013-04-22 09:26:27