c++/oop---运算符重载


c++/oop---运算符重载

重载为普通函数

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
class Complex{
    public :
        int a,b;
        Complex (int x=0,int y=0):a(x),b(y){}
        void outp(){
            printf("%d+%di\n",a,b);
        }
        Complex(const Complex &t){
            a=t.a,b=t.b;
            cout<<"haha"<

底下不加 const 和 & 的写法也是可以的,但是会调用复制构造函数,慢

重载为成员函数

Complex Complex::operator -(const Complex & t){
  return Complex(a-t.a,b-t.b);
}

此时只带一个参数

重载‘=’

=只能重载为成员函数

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
class String {
    private:
        char * str;
    public:
        String():str(new char[1]) { str[0] = 0; }
        const char * c_str() { return str; };
        String & operator = (const char * s);
        ~String() { delete [] str; }
};
String & String::operator=(const char * s) {//重载“=”以使得 obj=“hello”能够成立
    delete [] str;
    str = new char[strlen(s)+1];
    strcpy(str, s);
    return *this;
}
int main() {
    String s;
    s = "Good Luck," ; //等价于 s.operator=("Good Luck,");
    cout << s.c_str() << endl;
    // String s2 = "hello!"; //这条语句要是不注释掉就会出错
    s = "Shenzhou 8!"; //等价于 s.operator=("Shenzhou 8!");
    cout << s.c_str() << endl;
    return 0;
}

好厉害的写法

我现在感觉 String & operator 有一点用了

中间那句是因为构造函数没有定义

如果不定义自己的赋值号,那么 s1 = s2 会让 s1,s2指向同一个地方,可能会出现错误

但是这种写法 s = s 就会崩溃

这个时候可以判断下 this == &s then return *this

重载为友元函数

 可以解决左操作符不是类的对象的问题

比如 5 + c

#include 
#include 
#include 
#include 
#include 
using namespace std;
class Complex{
    public :
        int a,b;
        Complex (int x=0,int y=0):a(x),b(y){}
        void outp(){
            printf("%d+%di\n",a,b);
        }
        Complex(const Complex &t){
            a=t.a,b=t.b;
            cout<<"copy"<

注意几点

1:友元函数不是类里的函数,写到外面的时候不需要 Complex:: 

2. c2 = c1+2 的时候不会用到这个,此时程序会将 2 强制类型转换为 Complex

重载 ++

        Complex operator ++(){//before  ++c5
            a++;
            return *this;
        }
        Complex operator ++(int){//after  c5++
            Complex p=*this;
            a++;
            return p;
        }
        

格式如上

 重载[]

int & CArray::operator[](int i) {
//返回值为 int 不行! 不支持 a[i] = 4
 //用以支持根据下标访问数组元素,如 n = a[i] 和 a[i] = 4; 这样的语句
    return ptr[i];
 }

注意事项

运算符重载不改变运算符的优先级

以下运算符不能被重载:“.”、“.*”、“::”、“?:”、sizeof;

重载运算符 ()、[]、-> 或者赋值运算符 = 时,运算符重载函数必须声明为类的成员函数。 

重载强制类型转换符号

	operator int(){
		return nVal;
	}