我正试图创建一个书店程序,用于读取用户输入,直到EOF
。为了做到这一点,我超负荷istream >> operator
等。使用引用传递的指针重载
class CSales {
public:
//constructors
friend ostream & operator << (ostream &os, const CSales &x) const;
friend istream & operator >> (istream &is, const CSales &x);
//m_vars
};
istream & operator >> (istream &is, const CSales &x) {
/* following line prints error:
* no match for 'operator>>' */
if (is >> x.m_isbn >> x.m_price >> x.m_count) {
x.m_revenue = x.m_count*x.m_price; //assignment of member is read-only object
}
return is;
}
int main() {
vector<CSales*> dbs1;
CSales *candidate = new CSales();
while (cin >> *candidate) {
//sorted by isbn
auto iter = lower_bound(dbs1.begin(), dbs1.end(), candidate, cmp_isbn);
//operations
return 0;
}
我有一个怀疑,过载不工作,因为我试图通过使用参考指针。我在这个假设中纠正了吗?
我理解它的方式,
const CSales x
将是不正确的,因为我会改变指针,而不是我指向的对象。所以这可能会让我得到const CSales &*x
或const CSales *&x
。这两者有什么区别?我不知道为什么
x.m_revenue
行不起作用,为什么它只读,如果我没有运营商const
?
FULL CODE。我正在使用指向对象的指针向量,因为这应该使排序更有效率(只有移动指针,而不是对象本身)。
请注意,虽然输入和输出操作符在'CSales'类的范围内声明,但它们是* not *成员函数。因此你不能在输出运算符上使用'const'说明符。这会给你造成错误。 –
至于你的错误,你的输入操作符*修改*对象'x'。即它不能是'const'。 –
我现在明白我的'ostream'不应该有'const',但我没有'istream'中的'const'。 –