用引用的指针过载
Overloading with referenced-passed pointer
我正在尝试创建一个从用户读取输入直到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
?
,为什么只读它
完整代码。
编辑:我使用的是对象的指针向量,因为这应该使排序更有效(仅移动指针,而不是对象本身(。
这是问题:
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
合格。
相关文章:
- 如何使用基类指针引用派生类成员
- 将常量指针引用绑定到非常量指针
- 如果非动态变量被指针引用,何时超出范围?
- 转换指针引用的字符串
- 指针引用的生存期(以 C++为单位)
- 从 unique_ptr::get 发送指针作为指针引用进入函数
- 指针/引用的 CLion 格式
- 使用模板专用化来比较指针引用
- 如何保存指向抽象基类的指针/引用,但在 c++ 中仍然可以复制
- C++初始化指针/引用/复制细微差别
- 用数组或指针引用函数?
- 指针范围问题和返回类中封装的指针向量内的指针引用
- 强制转换为指针引用是否会导致未定义的行为
- 访问由 void 指针引用的结构的成员
- C 为什么当先前的步骤引发异常时,std :: shared_ptr的指针引用会被破坏
- 动态指针引用数组由三元运算符返回值,但有异常
- 悬空指向 int 和 char* 常量的指针/引用
- C++ 二维数组和指针引用
- 通过使用指针/引用,在C++中使用向量加快计算速度
- C++非类型模板模板到函数指针/引用