运算符重载">>"错误
operator overloading ">>" error
我正在尝试重载>>运算符。我为过载写了下面的代码,并试图在主要部分使用它。我有"无运算符">>"匹配这些操作数"和c2679错误。我浏览了一下互联网,但找不到解决方案。
这是我的操作员过载。
friend istream& operator >> (istream &in, Polynomial &polynomial)
{
in >> polynomial.e;
if (polynomial.e > 20)
throw "Bad Input!";
polynomial.x = new double[polynomial.e];
for (int i = 0; i < polynomial.e; i++) {
polynomial.x[i] = 0;
in >> polynomial.x[i];
}
return in;
}
并尝试将其与此代码一起使用。
out << "poly 1" << endl;
Polynomial *newPol1 = new Polynomial();
try {
cin >> newPol1;
}
catch (char* s)
{
cout << s << endl;
}
感谢
您正试图在指向此处类型Polynomial
的指针上使用std::cin
,如果必须使用指针,则更改
std::cin >> newPol1;
至
std::cin >> (*newPol1); // dereference pointer
不过,最好不要使用指针,而是直接使用,
Polynomial newPol1;
std::cin >> newPol1;
不需要新的:
Polynomial newPol1;
try {
std::cin >> newPol1;
}
...
或者,如果您真的想使用动态分配的对象,那么取消引用它
Polynomial *newPol1 = new Polynomial();
try {
std::cin >> (*newPol1); // notice the *
}
...
还有一些需要注意的地方。
if (polynomial.e > 20) // If things go bad.
// in a stream it is more normal
throw "Bad Input!"; // to set the bad bit on the stream.
// You can set the stream to throw an
// exception if required.
所以我本以为:
if (polynomial.e > 20) {
in.setstate(std::iosbase::failbit);
}
那么用法是:
if (std::cin >> newPol1) {
// it worked
}
else {
// it failed
}
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- 错误,包括&lt; ctype&gt;在原子上使用C 11
- 错误c++visual studio c2227左侧'->;Init';必须指向类/结构/联合/泛型类型
- opencv 2.4.7在iOS错误背景_segm.hpp #include&lt; list&gt;未找到
- 链接器(MinGW的ld v2.23.2)错误,格式:-L<SOMEDIR>-l<lib1-l<l