【发布时间】:2020-01-03 15:19:28
【问题描述】:
所以我的目标是将这个向量 vector 'Beer' allBeers 传递给函数 UnitedStatesBeer::getBeerTop(),但是当我尝试这样做时,我得到了函数调用中参数过多或我的对象未初始化的错误。
我该如何解决这个问题?感谢您的帮助!
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <vector>
using namespace std;
class RatingCalculator
{
public:
virtual void showCountryTop() = 0;
virtual void getCountryTop() {};
};
class Beer
{
public:
string name;
string rating;
string country;
string alc;
string type;
};
class UnitedStatesBeer : public RatingCalculator
{
private:
string name;
string rating;
string country;
string alc;
string type;
public:
void showCountryTop() {};
void getCountryTop(vector<Beer> allBeers){};
int main()
{
ifstream file("beer.txt");
Beer currentBeer;
vector<Beer> allBeers;
for (int i = 0; !file.eof(); i++)
{
getline(file, currentBeer.name, '\t');
getline(file, currentBeer.rating, '\t');
getline(file, currentBeer.country, '\t');
getline(file, currentBeer.alc, '\t');
getline(file, currentBeer.type, '\n');
allBeers.push_back(currentBeer); //copy all the information to allBeers vector
}
file.close();
/*if I do it this way*/
UnitedStatesBeer UsReassign;
UsReassign->getCountryTop(allBeers); //<- expression (UsReassign) must have pointer type/ Using uninitialized memory
// RatingCalculator* UsReassign = new UnitedStatesBeer();
// UsReassign-> getCountryTop(allBeers); //<- too many arguments in function call
}
【问题讨论】:
-
请创建一个minimal reproducible example 向我们展示,我们可以复制粘贴并自行尝试,无需以任何方式编辑或修改它。另外,请将完整且完整的错误输出复制粘贴到问题中(作为文本),因为通常会有有用的信息说明可以为问题提供提示。
-
一个提示:要覆盖虚函数,函数签名(例如参数)必须与基类中的完全相同。
-
为什么
UnitedStatesBeer有country属性?我希望看到class UnitedStatesBeer : public Beer,因为来自美国的啤酒是一种啤酒(嗯,至少有一部分是),而不是一种计算器。 -
请注意,您没有正确覆盖您的虚拟。
RatingCalculator::getCountryTop()与UnitedStatesBeer::getCountryTop(vector<Beer> allBeers).
标签: c++ function class object vector