【问题标题】:error: base operand of ‘->’ has non-pointer type ‘const’错误:“->”的基本操作数具有非指针类型“const”
【发布时间】:2018-04-08 23:57:37
【问题描述】:

我正在使用 ostream 运算符编写一个 c++ 链表,但我被卡住了。 我做错了什么?

// Train class
class Car{
    public:
        void print(ostream&) const;
        friend std::ostream &operator<<(std::ostream&, const Car&);
};

void Car::print(ostream& out) const{
        out << "OK" << endl;
 }

ostream& operator<<(ostream& os, const Car& car){
    os << car->print(os);
    return os;
}

错误:“->”的基本操作数具有非指针类型“const Car”
make: ***[Car.o] 错误 1

我尝试过的事情:
1) os print(*os);
2) 操作系统

【问题讨论】:

  • car.print(os) 而不是 car->print(os)
  • “情况变得更糟”,因为您还有另一个错误。把os &lt;&lt; car-&gt;print(os);改成car-&gt;print(os);,下次从更简单的代码开始,然后编译。
  • 错误: 'os Car::print(((std::) 中的 'operator
  • @Beta,感谢您的评论。那也不行。
  • 了解difference between a reference and a pointer,特别是不需要取消引用的事实。

标签: c++ class operator-overloading ostream


【解决方案1】:

我尝试过的事情:

1) 操作系统 print(*os);

base operand of ‘->’ has non-pointer type ‘const Car’

错误应该很清楚。您已在非指针(不重载该运算符的类型)上应用了间接成员访问运算符 -&gt;。这是你做不到的。据推测,您打算改为致电Car::print。这可以使用常规成员访问运算符 .

来完成
ostream& os
print(*os)

这是错误的。 ostream 没有间接运算符。由于print 接受ostream&amp; 作为参数,因此您可能打算将os 传递给函数。

void Car::print

Car::print 返回void,即它不返回任何值。然而,您将返回值插入到流中。您不能将void 插入流中。如果您打算从函数返回某些内容,则将返回类型更改为您打算插入到流中的任何内容。或者,如果您只打算在函数内将内容插入到流中,那么根本不插入函数的返回值:

当我们解决所有这三个问题时,我们最终会得到

car.print(os);

最后,Car::print 没有在 Car 的定义中声明。所有成员函数都必须在类定义中声明。声明应如下所示:

class Car{
    public:
        void print(ostream& out) const;
    // ...
}

【讨论】:

  • 感谢您的回复。是的,是我的错把我的职能搞混了。实际上, print() 已被声明。正如您提到的 void 函数不能接受返回类型作为 para,我将如何处理它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-09
相关资源
最近更新 更多