【发布时间】:2018-10-04 04:56:28
【问题描述】:
o,我正在尝试为向量创建重载输出运算符。假设这个重载的输出运算符允许我以格式打印向量中的值
[数据]^[索引] 例如,如果索引 3 处的数据是 4,它应该打印 3^4。
但是,我似乎无法让它正常工作。我需要它遍历整个向量,但我似乎无法检测到我做错了什么。
这是标题中的函数。
friend ostream & operator << (ostream &out, const vector<int> &c);
这是我在源文件中的函数。
ostream & operator << (ostream &os, const vector<int> &c)
{
for (int i = 0; i < c.size(); i++)
{
os << c.at[i];
os << "^";
os << i;
}
return os;
最后,这是我的主要内容
#include "Polynomial.h"
#include <string>
#include <vector>
#include <utility>
int main()
{
vector<int> poly1(10);
vector<int> poly2(10);
int x;
int y;
int choice;
bool done = true;
std::cout << "What do you wish to do?" << std::endl;
std::cout << "1. Add two polynomials" << std::endl;
std::cout << "2. Multiply two polynomials" << std::endl;
std::cout << "3. Evaluate one polynomial at a given value" << std::endl;
std::cout << "4. Find Coefficent for a given polynomial and given exponent" << std::endl;
std::cout << "5. Find the leading exponent for a given polynomial" << std::endl;
std::cout << "6. Exit "<< std::endl;
std::cin >> choice;
if (choice < 1 || choice > 6)
{
do
{
std::cout << "Invalid entry: please reenter choice" << std::endl;
std::cin >> choice;
} while (choice < 1 || choice > 6);
}
if (choice == 1)
{
std::cout << "Please input the first polynomial in the form of: (non-zero coefficient, exponent) pairs" << std::endl;
do
{
std::cin >> x >> y;
poly1.at(y) = x;
std::cout << "done?" << std::endl;
std::cin >> done;
} while (done == false);
std::cout << poly1 << std::endl;
}
if (choice == 2)
if (choice == 3)
if (choice == 4)
if (choice == 5)
if (choice == 6)
system("pause");
我相信我的问题存在于我的主文件或源文件中,尽管我很长时间没有使用过重载的输出运算符,所以我不确定需要修复什么。
【问题讨论】:
-
你应该得到
os << c.at[i];的编译器错误
标签: c++ vector output operator-overloading overloading