C++割付操作

998 ワード

1.オペレータの再ロード
1)リロードオペレータは、operatorの後にリロードするオペレータ名(operator=など)が続く関数です.
2)通常の関数と同様に、オペレータリロード関数には戻り値とパラメータのリストがあり、パラメータの数とオペレータのオペランドは同じです.たとえば=番号にはオペランドが2つあります.
3)オペレータがメンバーの場合、デフォルトの最初のパラメータはthisです.
2.代入オペレータ
1)割り当てオペレータで、2つのパラメータがあります.1番目のオペランドは左オペランド、2番目のパラメータは右オペランド
2)代入オペレータの戻り値とパラメータはすべて自身の参照である.
3例:
#include 
#include 

using namespace std;

class A
{
private:
	int pid;
	string name;
	int age;
public:
	A(){};
	A(int pid, string name, int age) :pid(pid), name(name), age(age){};
	void display();
	A& operator=(const A &a); 
};

A& A::operator=(const A &a)
{
	pid = a.pid;
	name = a.name;
	age = a.age;
	return *this;
}

void A::display()
{
	cout << pid << "," << name << "," << age << endl;
}

int main()
{
	A a;
	A a2(1,"tom",20);

	a = a2;//a=a.operator(const &a2)

	a.display();

	system("pause");
	return 0;