正常情况下我们不能对两个Class进行 = 、< 、等操作,通过重载操作符就可以了。
eg1:对 operator=
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout << "In A(): " << hex << (long)this << endl;
}
A(const A&)
{
cout << "In A(const A&): " << hex << (long)this << endl;
}
~A()
{
cout << "In ~A(): " << hex << (long)this << endl;
}
A& operator=(const A& a)
{
cout << "In operator=: " << hex << (long)this << " = " << hex << (long)(&a) << endl;
return *this;
}
};
A f()
{
A a;
return a;
}
int main(int argc, char* argv[])
{
A a;
a = f();
return 0;
}
eg2:这里有一个 类 person ,我们对这个类进行 = 、< 操作。
#pragma once
class person
{
public:
person(int _age=0):age(_age)
{
}
person& operator = (const person& a)
{
age=a.age;
return *this;
}
bool operator < (const person& a)
{
if(age<a.age)
{
return true;
}
return false;
}
private:
int age;
};
#include "person.cpp"
int main()
{
person a(1);
person b;
b=a;
person c(2);
if(a<c)
{
int qq=0;
}
return 0;
}