用引用的指针过载

Overloading with referenced-passed pointer

本文关键字:指针 引用      更新时间:2023-10-16

我正在尝试创建一个从用户读取输入直到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;
}
  1. 我怀疑该超负荷不起作用,因为我试图使用参考来传递指针。我在这个假设中是否正确?

  2. 我理解它的方式,const CSales x是不正确的,因为我会更改指针,而不是我指向的对象。这样可能会让我使用const CSales &*xconst CSales *&x。这两个区别有什么区别?

  3. 我不知道为什么x.m_revenue行不起作用,为什么如果我没有操作员为const

  4. ,为什么只读它

完整代码。

编辑:我使用的是对象的指针向量,因为这应该使排序更有效(仅移动指针,而不是对象本身(。

这是问题:

istream & operator >> ( istream &is, const CSales &x ) {
//                                   ^^^^^

这告诉编译器x constant ,您不会修改x。但是由于它是输入操作员,它肯定会修改x或没有多大意义。

错误消息" 的成员的分配只读对象"应该是一个非常清楚的提示。

您怀疑指针的问题是红鲱鱼(但我仍然建议您研究一种方法,而不是使用指针,在多态性之外,通常不需要现代C 中的指针(。


并澄清我的第一个评论:

class CSales {
public:
    ...
    friend ostream & operator << ( ostream &os, const CSales &x ) const;
    //                                                            ^^^^^
    ...
};

operator<<函数是A non-ember 函数,因此添加const限定符应导致构建。只有成员功能可以是const合格。