3

我希望重载“>>”运算符,以便有人可以输入任意数量的值。

这是我正在处理的作业的逐字逐句要求:

运算符>> 应该期望看到以下形式的输入:d v1 v2 … vd ,其中 d 是向量的维数,每个 vi 是向量中与索引 i 对应的值。

我假设它会起作用的方式是第一个值是数组的大小(包含在对象 Vex 中),其余的是元素。所以如果他们要输入

Vex vX;
4, 1, 2, 3, 4 >> vX; 

vX 将创建一个大小为 4 的动态数组,其中包含数字 1-4。

我挂断的主要部分是如何对 >> 重载进行编程,因为参数的数量是可变的。

理想情况下,我会对...的效果有一个解决方案(这只是一个例子):

std::istream& Vex::operator>>(istream& is, const Vex&){
   /*
     Assume int * data has been previously declared in constructor
     data = new int[iterator[0]]
     create iterator of input for istream
     For n from 1 to iterator[0]...
         data[n] = iterator[n] 
   */
}

我只是不知道该怎么做。我一直在环顾四周,找到了 istream_iterator,但我找不到任何人以我需要的方式使用它的好例子。

我希望我提供的信息足以回答这个问题。如果没有,请告诉我。

非常感谢您的宝贵时间。

4

4 回答 4

9

您的老师并没有要求您重载operator>>以获取可变参数列表。他要求您以这样一种方式重载operator>>,即它在运行时解析用户(或文件或任何istream对象)给出的可变长度输入。您需要的签名是这样的:

std::istream& operator>>(istream& is, Vex& v)

它不应该是成员函数,但您可能需要它成为朋友。

我对这个类一无所知Vex,所以我不能告诉你如何编写这个函数,但它会是这样的:

read an integer N from the stream
set size of Vex object as N, however that's done
for i = 1 to N
    read number X from the stream
    store X in Vex object at position i
于 2013-09-23T02:06:32.457 回答
0

您的参数列表需要用逗号分隔,然后您可以在一次operator<<调用中传递其中的几个。

OpenCV 就是这样做的。以下是它的使用方法(搜索逗号分隔): http ://docs.opencv.org/modules/core/doc/basic_structures.html?highlight=comma-separated#mat

看看他们的代码cv::Mat_https ://github.com/Itseez/opencv/blob/master/modules/core/include/opencv2/core/matx.hpp line 840

它使用一个辅助对象,你的任务是找出它是如何工作的。

于 2013-09-23T01:47:58.690 回答
0

请记住,逗号是运算符。它计算每个表达式并返回右侧操作数的值。此外,它从左到右关联。最后,>>具有比 更高的优先级,。这意味着

4, 1, 2, 3, 4 >> vX;

相当于

((((4, 1), 2), 3), (4 >> vX));

4, 1计算结果为1,因此上述计算结果为

(((1, 2), 3), (4 >> vX));

评估为

((2, 3), (4 >> vX));

评估为

(3, (4 >> vX));

评估为

4 >> vX;

所以要编译上面的语句,你必须重载

Vex& operator>>(int, Vex&);

从评论到您的原始问题,教授似乎希望您在课堂上operator>>超载Vex。这意味着签名应该是:

istream& operator>>(istream&, Vex&);
于 2013-09-23T02:04:46.177 回答
0

你想多了。更仔细地阅读规范。我认为以下内容非常接近所要求的内容。

GCC 4.7.3:g++ -Wall -Wextra -std=c++0x

#include <vector>
#include <iostream>
#include <string>
#include <sstream>

template <class T>
struct Vex {
  std::vector<T> v;
};

template <class T>
std::istream& operator>>(std::istream& is, Vex<T>& vex) {
  auto dim = 0;
  is >> dim;
  for (auto i = 0; i < dim; ++i) {
    T t;
    is >> t;
    vex.v.push_back(t);
  }
  return is;
}

int main() {
  std::stringstream is("4 1 2 3 4");
  Vex<int> vex;
  is >> vex;

  for (auto i : vex.v) {
    std::cout << i << " ";
  }

  return 0;
}
于 2013-09-23T02:10:39.157 回答