【发布时间】:2018-07-06 06:36:25
【问题描述】:
我不明白为什么第二个对象 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
【问题讨论】:
-
因为你是按值传递的。
-
当您将
d2传递给d1.compare时,它会进行复制,并且参数也会被破坏。 -
我认为这是由于
d1.compare(d2);,您通过值传递了d2,从而创建了data类的新实例。 -
您忘记添加日志以复制 ctor 和分配。
-
我相信这与指定的副本不是同一个问题。不同之处在于另一个问题解决了复制构造函数的存在,在这个问题中它似乎被忽略了,因此另一个答案的答案在这里无效
标签: c++ class object constructor destructor