【发布时间】:2014-07-25 14:51:57
【问题描述】:
为什么这个程序会写 45、125 和 300? 我知道 45 和 300,我对 sum1(arrD) 的情况更感兴趣,其中程序写入 125。 我希望有人会知道。
#include <iostream>
using namespace std;
class B{
public:
B(): b(bCounter++){}
int b;
static int bCounter;
};
int B::bCounter = 0;
class D : public B{
public:
D() : d(bCounter){}
int d;
};
const int N = 10;
B arrB[N];
D arrD[N];
int sum1(B* arr){
int s = 0;
for (int i=0; i<N; i++) s+=arr[i].b;
return s;
}
int sum2 (D* arr){
int s = 0;
for (int i = 0; i<N; i++) s+= arr[i].b + arr[i].d;
return s;
}
int main(){
cout<<" result is: "<<sum1(arrB)<<endl;
cout<<" result is: "<<sum1(arrD)<<endl;
cout<<" result is: "<<sum2(arrD)<<endl;
system("pause");
return 0;
}
静态数组 B arrB[N] 和 D arrD[N] 似乎在这里造成了麻烦。
【问题讨论】:
-
当您使用断点调试应用程序并观察值时发生了什么?
-
调试的时候不会去构造函数让我看b和d的值是多少。但我想出了另一种调试方式,Bb 是 0 1 2 3 4 5 6 7 8 9,Db 是 10 11 12 13 14 15 16 17 18 19,Dd 是 11 12 13 14 15 16 17 18 19 20。结果 125 是 10 + 11 + 11 + 12 + 12 + 13 + 13 + 14 + 14 + 15 但我不知道为什么这些值。
-
尽量不要将构造函数放在一行,以帮助调试。
-
你有错字吗?总和([10..19])= 145