【问题标题】:c++ overloading << operator errorc++重载<<操作符错误
【发布时间】: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++ 调用,您也会泄漏内存。

标签: c++ operator-overloading


【解决方案1】:

尝试以下方法:

void print_vector_elements(Vector& v)
{
  for(int i=0; i < i.size(); ++i) cout << v[i] << '\n'; 
}

关于重载插入操作符,检查:Overload ostream << operator

【讨论】:

  • 我知道如何打印元素,你没有回答我的问题,是的,我看过那个帖子。
  • @Cem Aytekin 我试图指出,如果您有具有多个数据成员的对象(基本上是矢量类型容器),打印其元素的更好方法可能是通过函数.运算符重载中的打印循环是一种罕见的事情,而且,第一次看到。但是,我可能是错的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-24
  • 1970-01-01
  • 1970-01-01
  • 2015-01-17
  • 2015-07-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多