operator重载整理

来源:互联网 发布:windows系统正版验证 编辑:程序博客网 时间:2024/05/20 12:51
     重载的操作符在类体中被声明,声明方式如同普通成员函数一样,只不过他的名字包含关键字operator,以及紧跟其后的一个c++预定义的操作符。
可以用如下的方式来声明一个预定义的==操作符:
class person{
private:
int age;
public:
person(int a){
this->age=a;
}
inline bool operator ==(const person &ps) const;
};
实现方式如下:
inline bool person::operator==(const person &ps) const
{ if (this->age==ps.age)
return true;
return false;
}
调用方式如下:
#include<iostream>
using namespace std;
int main()
{ person p1(10);
person p2(20);
if(p1==p2) cout<<”the age is equal!”< return 0; 
}
这里,因为operator ==是class person的一个成员函数,所以对象p1,p2都可以调用该函数,上面的if语句中,相当于p1调用函数==,把p2作为该函数的一个参数传递给该函数,从而实现了两个对象的比较。
考虑如下的if语句:
if(10==p1) cout<<”the age is equal!”< 是否回正确执行呢?
答案是不会的,因为只有左操作数是该类类型的对象的时,才会考虑作为类成员重载操作符。因为10不是person类型的对象,所以,不能调用classperson的操作符==。
考虑如下if语句:
if(person(10)==person(11))

cout<<"ok"< 是否能够正确执行呢?答案是可以,因为操作符两边均是无名对象。







拷贝构造函数和赋值运算符

本节内容较深,初学者请跳过。“拷贝构造函数”和“赋值运算符”都是将对象的值复制一份然后传给另一对象。这二个功能也是类本身就具有的,但有很多场合原封不动地复制给另外一个对象时反而会出错,例如在成员函数中有动态分配内存,或者参数指针指向外部某一地址时,就有可能出错。

要避免这些错误,我们可以重载“=”运算符以及拷贝构造函数,将出错的因素排除。下例中为了演示,故意将赋值运算符重载函数中不复制“姓名”,而拷贝构造函数中固定“年龄”。

#include <iostream>#include <string>using namespace std;class stuff {    string name;    int age;public:    stuff(string n, int a):name(n),age(a)    {        cout << "构造函数  " << name << age << endl;    }    string getName() {        return name;    }    int getAge() {        return age;    }    stuff& operator =(stuff& x);    //赋值运算符重载    stuff(stuff& x):name(x.name),age(20)    //拷贝构造函数重载    {        cout << "拷贝构造函数  " << name << age << endl;    }};stuff& stuff::operator =(stuff& x){    age = x.age;    cout << "赋值运算符  " << name << age << endl;    return *this;}int main ( ) {    stuff st("小雅", 25);     //调用通常的构造函数    stuff st1("劝学网", 2);   //调用通常的构造函数    st1 = st;         //因为不产生新的实例,所以调用的是赋值运算符    stuff st2 = st;   //因为产生新的实例,所以调用的是拷贝构造函数    cout << st.getName() << st.getAge() << endl;    cout << st1.getName() << st1.getAge() << endl;    cout << st2.getName() << st2.getAge() << endl;    return 0;}



当需要将当前类的实例直接赋值给其它类型的变量时自动转换类型,这其实还是运算符重载。当需要其它类型直接赋值给当前类的实例时,只要增加构造函数就行。

#include <iostream>#include <string>using namespace std;class stuff {    string name;    int age;public:    stuff(string n, int a):name(n),age(a) { }    string getName() {        return name;    }    int getAge() {        return age;    }    operator int() {     //stuff → int        return age;    }    operator string() {  //stuff → string        return name;    }};int main ( ) {    stuff st("小雅", 25);    string m_name = st; //stuff → string    int m_age = st;     //stuff → int    cout << m_name << endl;    cout << m_age << endl;    return 0;}