【发布时间】:2015-04-03 22:15:05
【问题描述】:
private:
int size;
int*head;
嗨,我正在设计一个向量类(用于数学)。我的目标是将向量打印为 [x1,x2,x3..xn]。我将构造函数设计为:
Vector::Vector(int x) :size(x){
size=x;
head=new int[x];
for(int i=0;i<size;i++){
head[i]=0; // all the elements initially 0
}
}
访问私有数据成员:
int*Vector::showthehead(){
return head;
}
int Vector::showthesize(){
return size;
}
我想按如下方式打印它们,但我有一个错误说:“'
ostream &operator<<(ostream &os,Vector &v){
// free function put in the cpp file but not in header.
int*x=new int[];
x=v.showthehead();
for(int i=0;i<v.showthesize;i++){
os<<" "<<x[i]<<" ";
}
return os;
}
【问题讨论】:
-
在
for循环中,您需要v.showthesize()。你错过了括号。你也不想要那个int *x = new int[];。你只想要int *x = v.showthehead();。 -
感谢 cmets,但问题是,主要是当我创建矢量并尝试打印它时,它不起作用
-
如果我做 const vector & v 那么我不能在 v 上使用成员函数
-
所以您的问题与主要发生的事情有关,但您没有显示主要功能 - 您看到问题的问题了吗?除此之外,您正在泄漏内存:
int*x=new int[];是错误的(您是 Java 程序员吗?)。请改写int*x=v.showthehead();。还请改进问题的格式。 -
int*x=new int[];这不是标准的 C++。即使您将其更改为new[]的标准 C++ 调用,您也会泄漏内存。