鱼C论坛

 找回密码
 立即注册
查看: 2572|回复: 3

C++运算符重载问题

[复制链接]
发表于 2012-5-1 16:52:16 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
/*+和++运算符重载*/
#include <iostream>
using namespace std;
class Test
{
public:
        Test(int a = 0)
        {
                Test::a = a;
        }
        Test operator +(Test& temp1,Test& temp2);
        Test operator ++(Test& temp);
public:
        int a;
};

Test Test::operator +(Test& temp1,Test& temp2)//+运算符重载函数
{
    Test result(temp1.a*temp2.a);
    return result;
}

Test Test::operator ++(Test& temp)//++运算符重载函数
{
    temp.a+=2;
    return temp;
}

int main()
{
    Test a(100);
    Test c=a+a;
    cout<<c.a<<endl;
    ++c;
    cout<<c.a<<endl;  
}
以上代码有什么问题!我编译出现很多错误!
小甲鱼最新课程 -> https://ilovefishc.com
发表于 2012-5-8 22:42:25 | 显示全部楼层
类里面成员函数不用写类参数
外面需要些
一般
2 + a才需要外面重载下
返回值右++返回const
左++返回引用比较好
小甲鱼最新课程 -> https://ilovefishc.com
 楼主| 发表于 2012-5-9 18:11:19 | 显示全部楼层
哦........
小甲鱼最新课程 -> https://ilovefishc.com
发表于 2012-5-11 13:14:52 | 显示全部楼层
#include<iostream>
class Test{
public:
     Test(int a=0){
         this->a=a;
      }
     Test(){}
    Test &operator+(Test temp1);
    Test &operator++();
public:
    int a;
};
Test &Test::operator+(Test temp1){
       return Test(this->a+temp1.a);
}
Test &Test::operator++(){
       return Test(++(this->a));
}
int main(){
   Test a(10);
   Test c=a+a;
   std::cout<<c.a;
   c++;
std::cout<<c.a;
    return 0;
}
//我是现写的,我也没有用编译器编译,所以你自己试一下,我觉得应该没有问题的哦
小甲鱼最新课程 -> https://ilovefishc.com
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-11-13 04:09

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表