c++重载运算符

来源:互联网 发布:淘宝旺旺名称在哪里看 编辑:程序博客网 时间:2024/06/07 22:44



本文内容已经移至我最新的个人博客,欢迎大家到我的新网站交流学习。 查看文章请点我。



























































































<span style="font-size:18px;">#include "stdafx.h"#include <iostream>using namespace std;class num{public:num(){n=new int;*n=3;}num(int i){n=new int;*n=i;}int get()const{return *n;}~num(){delete n;n=NULL;}//const num operator +(num &r){return (num(n+r.get()));}const num &operator =(const num &r){*n=r.get();return *this;}private:int *n;};int main(){num one(1),two,three;three=two=one;cout<<one.get()<<endl;cout<<two.get()<<endl;cout<<three.get()<<endl;system("pause");return 0;}</span>

当成员变量是指针的时候,重载运算符要注意使用深拷贝或者直接返回一个引用,避免发生错误