我已经看到许多其他问题出现相同的错误,但这些问题来自没有重载 >> 运算符的人。我在编写的其他一些程序中遇到了这个问题,因为它们都是练习题,所以彼此非常相似。
我还查看了我的教科书并将我的程序与他们的示例程序进行了比较,但看不出我哪里出错了。
完整的错误是(在 main.cpp 中)
第 17 行:错误:“operator>>”不匹配(操作数类型为“std::ifstream {aka std::basic_ifstream}”和“Suitcase()”)|
非常感谢任何和所有建议。
我的标题是
//suitcase.h
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#ifndef SUITCASE_H
#define SUITCASE_H
using namespace std;
class Suitcase
{
public:
Suitcase();
Suitcase(double p,double w,double v,string s,string b);
~Suitcase();
double calc_ratio();
friend bool operator>(const Suitcase s1,const Suitcase s2);
friend ostream& operator<<(ostream & out,const Suitcase& s);
friend istream& operator >>(istream& in,Suitcase& s);
private:
double price,weight,volume;
string brand,shop;
};
#endif // SUITCASE_H
我的实现是
//suitcaseimplement.cpp
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#include "suitcase.h"
using namespace std;
Suitcase::Suitcase()
{
price=0;
weight=0;
volume=0;
shop="";
brand="";
}
Suitcase::Suitcase(double p,double w,double v,string s,string b)
{
price=p;
weight=w;
volume=v;
shop=s;
brand=b;
}
Suitcase::~Suitcase()
{
}
double Suitcase::calc_ratio()
{
return (volume/weight);
}
bool operator>(Suitcase s1,Suitcase s2)
{
if(s1.calc_ratio()>s2.calc_ratio())
return true;
}
ostream& operator<<(ostream & out,const Suitcase& s)
{
out<<"The suitcase with the highest ratio is the "<<s.brand<<endl;
out<<"It is available at "<<s.shop<<endl;
out<<"It weighs "<<s.weight<<"kgs, has a volume of "<<s.volume<<"and costs R"<<s.price<<endl;
return out;
}
istream& operator >>(istream& in,Suitcase& s)
{
in>>s.price>>s.weight>>s.volume>>s.brand>>s.shop;
return in;
}
最后是我的主程序。
//main.cpp
#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
#include "suitcase.h"
using namespace std;
int main()
{
ifstream infile;
infile.open("Suitcase.txt");
if(infile.fail())
exit(1);
Suitcase current_suitcase(), best_suitcase();
infile>>best_suitcase;
while(infile>>current_suitcase)
{
if(current_suitcase>best_suitcase)
{
current_suitcase=best_suitcase;
}
}
infile.close();
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout<<best_suitcase;
return 0;
}
最佳答案
这一行
Suitcase current_suitcase(), best_suitcase();
声明两个返回 Suitcase
的函数,而不是定义两个变量。这称为 Most vexing parse规则。删除多余的括号可以解决问题:
Suitcase current_suitcase, best_suitcase;
另外,不要做 using namespace std .
关于c++ - 不断收到错误 ' no match for ' operator>>' ;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58915888/