gpt4 book ai didi

c++ - 为什么在以下代码中调用析构函数?

转载 作者:太空狗 更新时间:2023-10-29 23:23:18 30 4
gpt4 key购买 nike

考虑以下代码。此代码取自本书 Object Oriented Programming With C++ !-第 12 章模板。

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
class vc
{
int size2;
int *v;
public :

vc(int size1);
vc(int *a);
~vc()
{
printf("\n calling destructor");
}
int operator *(vc );
};
vc::vc(int size1)
{
v = new int[size2=size1];
for(int i=0;i<this->size2;i++)
v[i]=0;
}
vc::vc(int a[])
{

for(int i=0;i<this->size2;i++)
{
v[i]=a[i];

}
}
int vc::operator *(vc v1)
{
int total=0;
for(int i=0;i<size2;i++)
total+=(v[i]*v1.v[i]);
return total;
}

int main()
{
int a[3]={1,2,3};
int b[3]= {5,6,7};
vc v1(3),v2(3);
v1=a;
v2=b;
int total = v1*v2;
cout << total;
return 0;
}

首先,这段代码不能正常工作。它应该显示 38 作为输出。当我开始调试这段代码时,我发现 3 在这行 vc v1(3),v2(3); 之后分配给了 size2。但是在执行下一行时,控制被传递给第二个构造函数并且 size2 显示了一个垃圾值。此外,析构函数在 v1=a 行之后调用,同样的情况发生在下一行之后。

最终输出:

调用析构函数
调用析构函数
调用析构函数0

为什么析构函数被调用了 3 次?这段代码有错吗?

最佳答案

当你调用v1*v2时,你将v2传递给方法

int vc::operator *(vc v1)

创建 v2 的本地拷贝。因此,您有一个额外的 vc 实例。

第一个疑惑的答案,

But while executing the next line, control is passed to the second constructor and size2 shows a garbage value and it is not executed for three times.

是因为

v1 = a;

通过调用 vc::vc(int a[]) 创建一个临时的 vc 并将其分配给 v1。但是,此构造函数没有初始化 size2。所以你得到一个垃圾值。

更简洁的方法是传递数组及其大小:

vc::vc(int a[], int size1) {                                                                                       
v = new int[size2=size1];
for(int i=0; i<size2; i++)
v[i] = a[i];
}

int main()
{
int a[3]={1,2,3};
int b[3]= {5,6,7};
vc v1(a, 3), v2(b, 3);
int total = v1*v2;
cout << total;
return 0;
}

那么 total 将是 38。

关于c++ - 为什么在以下代码中调用析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18150047/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com