运算符重载

运算符重载

转换构造函数/类型转换函数

https://blog.csdn.net/lzm18064126848/article/details/50457636
eg 将double和Complex相加

operator double(){
	return real;
}
#include<iostream>
using namespace std;
class Complex{
    private:
        double z,f;
    public:
        Complex(){}
        Complex(double z_){
            z=z_;
            f=0;
        }
        Complex(double z_,double f_){
            z=z_;
            f=f_;
        }
        friend Complex operator + (const Complex &c1, const Complex &c2){
            return Complex(c1.z + c2.z, c1.f + c2.f);
        }

        friend Complex operator + (double d, const Complex &c){
            return Complex(d + c.z, c.f);
        }

        friend Complex operator + (const Complex &c, double d){
            return Complex(c.z + d, c.f);
        }
        friend ostream& operator<<(ostream& out, const Complex& c) {
            out << "(" << c.z << ", " << c.f << "i)";
            return out;
        }
};
int main(){
    Complex c1(5.5,6.3);
    Complex c2(4.1,7.6);
    double i=0.3;
    Complex c3=c1+c2;
    Complex c4=i+c1;
    Complex c5=c1+i;
    cout<<c3<<" "<<c4<<" "<<c5;
    return 0;
}

关于+-*/<< >> 的重载

注意书写格式
friend Martix operator + (const Martix &a,const Martix &b)
friend ostream & operator << (ostream &output,const Martix &a)

#include<iostream>
#include<cstring>
using namespace std;
class Martix{
    private:
        int num[2][3];
    public:
        Martix(){
            memset(num,0,sizeof num);
        }
        Martix(int num_[2][3]){
            for(int i=0;i<2;i++){
                for(int j=0;j<3;j++){
                    num[i][j]=num_[i][j];
                }
            }
        }
        friend Martix operator + (const Martix &a,const Martix &b){
            Martix ans;
            for(int i=0;i<2;i++){
                for(int j=0;j<3;j++){
                    ans.num[i][j]=a.num[i][j]+b.num[i][j];
                }
            }
            return ans;
        }
        friend ostream & operator << (ostream &output,const Martix &a){
            for(int i=0;i<2;i++){
                for(int j=0;j<3;j++){
                    cout<<a.num[i][j]<<" ";
                }
                cout<<endl;
            }
            return output;
        }
};
int main(){
    int a_[2][3]={{1,2,3},{4,5,6}};
    int b_[2][3]={{2,3,4},{5,6,7}};
    Martix a(a_),b(b_);
    cout<<(a+b)<<endl;
    return 0;
}
posted @ 2026-01-20 20:48  White_ink  阅读(2)  评论(0)    收藏  举报