c++运算符的重载

来源:互联网 发布:重生之一叶而知秋书包 编辑:程序博客网 时间:2024/06/02 06:39

先通过一个例子理解运算符的重载

#include<iostream>using namespace std;class Complex{private:    double real;//实部    double imag;//虚部public:    Complex(double real = 0, double imag = 0);//构造函数    ~Complex();//析构函数    void display();//显示    Complex operator+(Complex &y);//重载运算符};Complex::Complex(double real, double imag){    this->real = real;    this->imag = imag;}Complex::~Complex(){    cout << "Finished" << endl;}Complex Complex::operator + (Complex &y){    return Complex(real+y.real,imag+y.imag);}void Complex::display(){    cout << real << "+" << imag << "i" << endl;}int main(){    Complex x(1.9, 1.2), y(2, 8), z;    z = x + y;    z.display();    system("pause");    return 0;}

C++运算符重载的一些规定

1. C++不允许用户自己定义新的运算符,只能对已有的运算符进行重载

2.不能重载的运算符有5个

运算符 意义 . 成员访问运算符 * 成员指针访问运算符 :: 域运算符 sizeof 长度运算符 ?: 条件运算符

3.重载不能改变运算符运算对象的个数
4. 重载不能改变运算符的优先级别
5. 重载不能改变运算符的结合性
6.重载运算符不能有默认的参数
7.重载运算符必须和用户定义的自定义类型的对象一起使用,其参数至少应有一个是类对象(或类对象的引用)
8. 用于类对象的运算符一般必须重载,但有两个例外“=”“&”
9.理论上讲,可以将运算符重载为执行任意的操作


对运算符重载的函数有两种处理方式
1.作为类的成员函数
2.作为类的友元函数
c++对个别运算符有一些强制规定

成员函数 友元函数 = << [ ] >> ( ) ->

双目运算符的重载

#include<iostream>using namespace std;class String{private:    char *p;public:    String(char *p = NULL);//带默认参数的构造函数    ~String();//析构函数    void set(char *p);    void display();//显示    friend bool operator>(String &a, String &b);//重载  >    friend bool operator<(String &a, String &b);//重载  <    friend bool operator==(String &a, String &b);//重载  ==};String::String(char *p ){    set(p);}String::~String(){    cout << "finished" << endl;}void String::set(char *p){    this->p = p;}void String::display(){    cout << p << endl;}bool operator>(String &a, String &b){    if (strcmp(a.p, b.p)>0) return true;    else return false;}bool operator<(String &a, String &b){    if (strcmp(a.p, b.p)<0) return true;    else return false;}bool operator==(String &a, String &b){    if (strcmp(a.p, b.p)==0) return true;    else return false;}int main(){    String s1("hello"), s2("hello");    cout << (s1 > s2) << endl;    cout << (s1 < s2) << endl;    cout << (s1 == s2) << endl<<endl;    s1.set("asasaaas");    cout << (s1 > s2) << endl;    cout << (s1 < s2) << endl;    cout << (s1 == s2) << endl;    system("pause");    return 0;}

重载单目运算符

未完,待续。。。

原创粉丝点击