【发布时间】:2019-11-18 13:38:37
【问题描述】:
我已经看到许多其他具有相同错误的问题,但这些问题来自没有重载 >> 运算符的人。我编写的其他一些程序都遇到了这个问题,因为它们都是练习题。
我还查看了我的教科书,并将我的程序与他们的示例程序进行了比较,但看不出我哪里出错了。
完整的错误是(在 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;
}
【问题讨论】:
-
非常抱歉您可能发现的其他错误和错误。
-
查找“最令人头疼的解析”以了解正在发生的事情。
-
我未能以更简洁的minimal reproducible example:MCVE on Compiler Explorer 重现您的问题。显然,我错过了
Suitcase current_suitcase(), best_suitcase();的实际问题。 ;-)
标签: c++ c++11 file-io operator-overloading