秋名山小法师 2016-02-08 21:29 采纳率: 33.3%
浏览 1500
已采纳

一个关于c++构造函数和运算符重载的问题

代码如下,具体情况是,我定义了一个有形参的构造函数和+号运算符重载,我觉得两个是独立的,但是在调用+号运算符重载时发现同时又调用了这个构造函数,因为我在函数里写了输出语句,所以被调用时我能看到,c++小白想请问各位大神是为什么?是运算符重载函数写的有问题吗?多谢各位~~
//constructeur 2
BigInt::BigInt(int n):numDigits(0)
{
cout << "constructeur 2 bien appelé" << endl;
int quotient = n;
int residu;
cout << "l'entier que vous donnez est ";
for(int i=0;i {
numDigits++;
residu = quotient%10;
quotient = quotient/10;
vals[i] = residu;
if(residu == 0 && quotient == 0)
{
break;
}
cout }
cout cout }
//surcharge de l'operateur+
BigInt BigInt::operator+(const BigInt& a)
{
cout int temp[3000];
int r = 0;
for(int i=0;i {
temp[i] = vals[i] + a.vals[i] + r;
if(temp[i]>9)
{
r = 1;
temp[i] -= 10;
}
else{r = 0;}
cout << temp[i] << " ";
}
cout << endl;
return temp[numDigits];
}

  • 写回答

2条回答

  • threenewbee 2016-02-08 23:15
    关注

    你的判断是对的,重载的运算符会调用拷贝构造函数,把结果放在堆栈上,看下面的最简单的程序

    #include <iostream>
    using namespace std;
    class A
    {
    public:
        A() { cout << "A()" << endl; }
        A(A& o){ cout << "A(A& o)" << endl; }
        A operator+(A& o){ return o; }
    };
    int main()
    {
        A a, b;
        a + b;
        return 0;
    }
    

    A()
    A()
    A(A& o)
    Press any key to continue

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题