C++之重载操作符

时间:2022-04-11 21:43:35

1.类中重载+操作符

#define  _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std; class Object
{
public:
Object()
{ } Object(int a)
{
num = a;
} Object operator + (const Object& a) //重载+操作符;
{
Object result;
result.num = num + a.num;
return result;
}
private:
int num;
}; int main(int argc, char * argv[])
{
int a = ;
int b = ; Object obja(a);
Object objb(b); Object objc = obja + objb; system("pause");
return ;
}

2.重载全局操作符

 

#define  _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std; class Object
{
friend Object operator + (const Object &a, const Object &b);
public:
Object()
{ } Object(int a)
{
num = a;
} private:
int num;
}; Object operator + (const Object &a, const Object &b)
{
Object result;
result.num = a.num + b.num;
return result;
} int main(int argc, char * argv[])
{
Object obja();
Object objb(); Object objc = obja + objb; system("pause");
return ;
}

全局操作符,主要注意的是,当重载操作符访问私有成员时,需要将操作符声明为友元;

4. 重载[] 操作符

#define  _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std; class Object
{
public:
Object()
{
} Object(char * str)
{
int size = strlen(str);
m_buf = new char[size];
strcpy(m_buf,str);
} char& operator [] (int index)
{
return m_buf[index];
} ~Object()
{
delete[] m_buf;
} private:
char *m_buf;
}; int main(int argc, char * argv[])
{
Object obja("weiyouqing"); char str = obja[];
obja[] = 'W'; system("pause");
return ;
}

5.重载==操作符

#define  _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std; class Object
{
public:
Object()
{
} Object(int a)
{
num = a;
} bool operator == (const Object &other)
{
if (num == other.num)
return true;
else
return false;
} ~Object()
{ } private:
int num;
}; int main(int argc, char * argv[])
{
Object obja();
Object objb();
if (obja == objb)
cout << "equal" << endl;
else
cout << "not equal" << endl; system("pause");
return ;
}

全局重载操作符:

#define  _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std; class Object
{
friend bool operator == (const Object &a, const Object &b);
public:
Object()
{
} Object(int a)
{
num = a;
} ~Object()
{ } private:
int num;
}; bool operator == (const Object &a,const Object &b)
{
if (a.num == b.num)
return true;
else
return false;
} int main(int argc, char * argv[])
{
Object obja();
Object objb();
if (obja == objb)
cout << "equal" << endl;
else
cout << "not equal" << endl; system("pause");
return ;
}