【发布时间】:2020-03-21 19:16:39
【问题描述】:
此代码给出了分段错误 在此程序中专门将数组分配给模板时是否调用了构造函数? 请详细解释 如果调用构造函数为什么是分段错误? if not called 这不是语法错误吗
#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;
}
【问题讨论】:
-
这个doesn't even compile 因为
using namespace std;。似乎是一本糟糕的书。 -
using namespace std;+class vector有足够的理由再也不打开这本书了 -
类的第一个可怕名称,尤其是在整个
std命名空间which you shouldn't do中啜饮时。一定要告诉我们书名和作者。我需要知道我的图书馆里是否有这些垃圾。 -
如果这是一本书的代码,我建议您将这本书重新用于学习 C++ 以外的其他内容。
-
请发布真实代码,这不会导致段错误,因为它确实not compile
标签: c++ arrays templates constructor runtime-error