秋名山小法师 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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog