我无法理解为什么第二个对象d2的析构函数被调用两次。我知道过去曾问过这类问题,但每一个问题都与我的有一些相关之处。任何帮助将不胜感激。谢谢。
#include <iostream>
using namespace std;
class data{
char s1[50];
static int j;
public:
data(char s[50]){
for(int i = 0; i < 50; i++){
s1[i] = s[i];
}
}
void show(){
cout <<"Data " << ++j <<"=" << s1 << endl;
}
void compare(data d){
for(int i = 0; i < 50; i++){
if(d.s1[i] != s1[i]){
cout << "Both Objects have different text." << endl;
break;
}
}
}
~data(){
cout << "Release memory allocated to " << s1 << endl;
}
};
int data::j;
int main(){
char str[50],str1[50];
cin>>str;
cin>>str1;
data d1(str);
data d2(str1);
d1.show();
d2.show();
d1.compare(d2);
return 0;
}
此代码运行时的输出是:
Data 1=object1
Data 2=object2
Both Objects have different text.
Release memory allocated to object2
Release memory allocated to object2
Release memory allocated to object1
答案 0 :(得分:5)
因为您是按值而不是通过引用将输入参数传递给compare
。