自定义数据类型与运算符重载
运算符重载的实质是函数重载
返回值类型 operator 运算符(形参表)
{
……
}
运算符可以被重载成普通函数
也可以被重载成类的成员函数
#include<iostream> using namespace std; /*运算符重载为普通函数 重载为普通函数时, 参数个数为运算符目数 */ #if 0 class Complex { public: double real; double imaginary; Complex(double r = 0.0, double i = 0.0) { real = r; imaginary = i; }// “类名(参数表)” 就代表一个对象 }; Complex operator+(const Complex & a, const Complex & b) { return Complex(a.real + b.real, a.imaginary + b.imaginary); } int main() { Complex a(1, 2), b(2, 3), c; c = a + b; cout << c.real << "," << c.imaginary << endl; while (1); return 0; } #endif /*运算符重载为成员函数 重载为成员函数时, 参数个数为运算符目数减一 */ class Complex { private: double real; double imaginary; public: // constructor Complex(double r = 0.0, double m = 0.0) :real(r), imaginary(m) {} Complex operator+(const Complex &); //addition Complex operator-(const Complex &); //subtraction }; //overloaded addition operator Complex Complex::operator+(const Complex & operand2) { return Complex(real + operand2.real, imaginary + operand2.imaginary); } //overloaded subtraction operator Complex Complex::operator-(const Complex & operand2) { return Complex(real - operand2.real, imaginary - operand2.imaginary); } int main() { Complex x, y(4.3, 8.2), z(3.3, 1.1); x = y + z; x = y - z; return 0; }
赋值运算符“=” 只能重载为成员函数
编写一个长度可变的字符串类String
包含一个char * 类型的成员变量
指向动态分配的存储空间
该存储空间用于存放‘ ’ 结尾的字符串
重载赋值运算符的意义–浅复制和深复制
防止内存垃圾的产生
深复制/深拷贝
将一个对象中指针变量指向的内容,
复制到另一个对象中指针成员对象指向的地方
#define _CRT_SECURE_NO_WARNINGS #include<iostream> using namespace std; class String { private: char * str; public: String() :str(NULL) {} //构造函数, 初始化str为NULL const char* c_str() { return str; } char* operator = (const char* s); ~String(); }; //重载‘=’ obj= “hello”能够成立 char* String::operator=(const char* s) { if (str) delete[] str; if (s) //s不为NULL才会执行拷贝 { str = new char[strlen(s) + 1];//+1存放' ' strcpy(str, s); } else str = NULL; return str; } String::~String() { if (str) delete[] str; } int main() { String s; s = "good luck,"; cout << s.c_str() << endl; //String s2 = "hello!"; //这条语句要是不注释掉就会出错,需要复制构造函数 s = "shenzhou 8!"; cout << s.c_str() << endl; while (1); return 0; }
运算符重载为友元函数
通常, 将运算符重载为类的成员函数
重载为友元函数的情况:
成员函数不能满足使用要求
普通函数, 又不能访问类的私有成员
#define _CRT_SECURE_NO_WARNINGS #include<iostream> using namespace std; /*普通函数不能访问私有成员 将运算符+重载为友元函数 */ class Complex { double real, imag; public: Complex(double r, double i) :real(r), imag(i) {}; Complex operator+(double r); friend Complex operator+(double r, const Complex & c); }; // 成员函数 Complex Complex::operator+(double r)//能解释 c+5 { return Complex(real + r, imag); } // 友元函数 普通函数 能解释 5 + c Complex operator+(double r, const Complex & c) { return Complex(c.real + r, c.imag); } int main() { Complex c(1,2); c = c + 5; c = 5 + c; return 0; }