我正试图超载'<<<<&#运算符正确,但我在尝试编译时遇到错误。
以下是我到目前为止的代码:
Sandwich.h:
#ifndef SANDWICH_H_
#define SANDWICH_H_
#include <string>
#include <iosfwd>
class Sandwich
{
public:
// Constructors
Sandwich(std::string name, float price) : name(name), price(price) {}
Sandwich() : name("Sandwich"), price(0.00) {}
// Accessor Functions
std::string getName() const { return name; }
float getPrice() const { return price; }
// Other Functions
friend std::ostream& operator<<(std::ostream& os, const Sandwich& object);
friend bool operator==(Sandwich &sandwich1, Sandwich &sandwich2);
friend bool operator!=(Sandwich &sandwich1, Sandwich &sandwich2);
friend bool operator<(Sandwich &sandwich1, Sandwich &sandwich2);
friend bool operator>(Sandwich &sandwich1, Sandwich &sandwich2);
friend bool operator<=(Sandwich &sandwich1, Sandwich &sandwich2);
friend bool operator>=(Sandwich &sandwich1, Sandwich &sandwich2);
private:
// Data Fields
std::string name;
float price;
};
#endif
Sandwich.cpp:
#include "Sandwich.h"
#include <ostream>
using std::ostream;
bool operator==(Sandwich &sandwich1, Sandwich &sandwich2)
{
if (sandwich1.getName()==sandwich2.getName() && sandwich1.getPrice()==sandwich2.getPrice())
{
return true;
}
else
{
return false;
}
}
bool operator!=(Sandwich &sandwich1, Sandwich &sandwich2)
{
if (sandwich1.getName()!=sandwich2.getName() && sandwich1.getPrice()!=sandwich2.getPrice())
{
return true;
}
else
{
return false;
}
}
bool operator<(Sandwich &sandwich1, Sandwich &sandwich2)
{
if (sandwich1.getPrice()<sandwich2.getPrice())
{
return true;
}
else
{
return false;
}
}
bool operator>(Sandwich &sandwich1, Sandwich &sandwich2)
{
if (sandwich1.getPrice()>sandwich2.getPrice())
{
return true;
}
else
{
return false;
}
}
bool operator<=(Sandwich &sandwich1, Sandwich &sandwich2)
{
if (sandwich1.getPrice()<=sandwich2.getPrice())
{
return true;
}
else
{
return false;
}
}
bool operator>=(Sandwich &sandwich1, Sandwich &sandwich2)
{
if (sandwich1.getPrice()>=sandwich2.getPrice())
{
return true;
}
else
{
return false;
}
}
ostream& operator<<(ostream& os, const Sandwich& object)
{
os << "Sandwich name: " << object.getName << "\nSandwich price: " << object.getPrice << '\n';
return os;
}
这个类最终将成为4个子类的基类。我试图确保它在继续之前有效,但它不能正确编译,我得到的错误是:
Sandwich.cpp: In function ‘std::ostream& operator<<(std::ostream&, const Sandwich&)’:
Sandwich.cpp:86:26: error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream<char>’ and ‘<unresolved overloaded function type>’)
os << "Sandwich name: " << object.getName << "\nSandwich price: " << object.getPrice << '\n';
^
还有一堆可能的候选人。
不太确定我哪里出错了,我以为我已经正确地重载了操作员。
答案 0 :(得分:1)
您需要使用()
os << "Sandwich name: " << object.getName() << "\nSandwich price: " << object.getPrice() << '\n';