次のコードを検討してください。このコードは、本 Object Oriented Programming With C++ !-Chapter 12.Templates からの抜粋です。
#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
割り当てられていることがわかりました。ただし、次の行を実行している間、コントロールは2番目のコンストラクターに渡され、ごみの値が表示されます。さらに、デストラクタはライン後に呼び出され、次のラインの後にも同じことが起こります。size2
vc v1(3),v2(3);
size2
v1=a
最終出力:
calling destructor
calling destructor
calling destructor0
Destructorが3回呼び出されるのはなぜですか?このコードは間違っていますか?