gpt4 book ai didi

c++ - 调用了 2 个重载的运算符>>方法

转载 作者:行者123 更新时间:2023-11-27 23:01:45 24 4
gpt4 key购买 nike

我有一个 Complex 类,它有两个重载的 operator>> 方法,一个用于来自控制台的 std::istream,第二个用于 std::ifstream.

std::istream& operator>>(std::istream& is, Complex& c) 
{

int re, im;
std::cout << "input the real-part of the complex" << std::endl;
while ( ! (is >> re))
{
std::cout << "Please give me a double! Try again: \n";
is.clear();
is.ignore(1000, '\n');
}
std::cout << "input the imaginary-part of the complex" << std::endl;
while ( ! (is >> im))
{
std::cout << "Please give me a double! Try again: \n";
is.clear();
is.ignore(1000, '\n');
}
c = Complex(re, im);
return is;
}

std::ifstream& operator>>(std::ifstream& ifs, Complex& c)
{
int re, im;
ifs >> re; ifs>> im;
c = Complex(re,im);
return ifs;
}

在我的程序中,我能够从控制台或文件中插入复数数组。为了简化插入,我创建了额外的方法:

void insertArray(std::istream& is, Complex* arr, int size)
{
for (int i = 0; i < size; ++i)
{
is >> arr[i];
}
}

不幸的是,我注意到当使用 std::ifstream 对象作为参数调用此方法时,

std::ifstream ifs("complex.dat");
insertArray(ifs, x, size);

both operator>> 方法被调用,所以控制台包含额外的输出,但是数据是从文件中正确加载的。结果如图所示。
console output
很容易注意到程序要求控制台缓冲区的给定值,但是从文件缓冲区加载数据。

除了使用 std::ifstream 而不是 std::istream 来创建单独的方法 insertArray2 之外,还有什么方法可以处理它吗?

最佳答案

您可以考虑模板化 insertArray:

template<class T>
void insertArray(T& is, Complex* arr, int size)

关于c++ - 调用了 2 个重载的运算符>>方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26877355/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com