我希望重载“>>”运算符,以便有人可以输入任意数量的值。
这是我正在处理的作业中的逐字要求:
Operator>> should expect to see input in the following form: d v1 v2 … vd , where d is the dimensionality of the vector and each vi is the value corresponding to index i in the vector.
我假设它的工作方式是第一个值是数组的大小(包含在对象 Vex 中),其余值是元素。所以如果他们输入
Vex vX;
4, 1, 2, 3, 4 >> vX;
vX 将创建一个包含数字 1-4 的大小为 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,但我找不到任何以我需要的方式使用它的好例子。
我希望我提供的信息足以回答这个问题。如果没有,请告诉我。
非常感谢您的宝贵时间。
最佳答案
你的老师并没有要求你重载 operator>>
来获取可变参数列表。他要求您重载 operator>>
,使其在运行时解析用户提供的可变长度输入(或文件,或任何 istream
对象)。您需要的签名是这样的:
std::istream& operator>>(istream& is, Vex& v)
它不应该是一个成员函数,但你可能需要它来成为一个 friend 。
我对这个 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
关于c++ - 如何重载 >> 运算符以获取可变参数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18950680/