我只是在寻找模板,在我的书中找到了这段代码,这显示了隔离错误?

I was just looking template and found this code in my book and this is showing segmantation fault?

本文关键字:代码 错误 隔离 显示 找到了 寻找 我的书 段代码      更新时间:2023-10-16

此代码给出了隔离错误 在此程序中专门将数组分配给模板时是否调用构造函数? 请详细解释 如果构造函数被调用,为什么是隔离错误? 如果未调用,这不是语法错误吗

#include <iostream>
using namespace std;
const int size=3;
template<class T>
class vector{
T *v;
public:
vector(){
v = new T[size];
for(int i=0;i<size;i++)
{
v[i]=0;
}
}
vector(T *a){
for (int i=0;i<size;i++)
{
v[i]=a[i];
}
}
T operator*(vector &v){
T sum=0;
for (int i=0;i<size;i++)
{
sum+=this->v[i]*v.v[i];
}
return sum;
}
void display(){
for (int i=0;i<size;i++)
{
cout << v[i] <<"t";
}
}
};
int main()
{
int x[3]={1,3,5};
int y[3]={2,4,6};
vector<int> v1;
vector<int> v2;
v1=x;
v2=y;
v1.display();
cout<<endl;
v2.display();
return 0;
}

除了所有糟糕的代码之外,还有一个问题:

int x[3]={1,3,5};
...
vector<int> v1(x);

其中调用:

template<class T>
class vector{
T *v;
...
public:
vector(T *a){
for (int i=0;i<size;i++)
{
v[i]=a[i];
}
}
...

因为指针v尚未分配任何内存。 所以第一次通过for循环:v[0] = a[0];会造成分段错误。