错误:"->"的基本操作数具有非指针类型"const"

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

本文关键字:操作数 指针 const 类型 gt 错误      更新时间:2023-10-16

我正在使用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);
2) 操作系统<<car.print(os);情况变得更糟

我尝试过的事情:

1) 操作系统<<汽车>打印(*OS);

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

错误应该很清楚。您已在非指针(不会重载该运算符的类型)上应用了间接成员访问运算符->。这是你不能做的事情。大概,你打算打电话给Car::print。这可以使用常规成员访问运算符.

ostream& os
print(*os)

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

void Car::print

Car::print返回void即它不返回任何值。但是,您将返回值插入到流中。不能将void插入到流中。如果您打算从函数返回某些内容,请将返回类型更改为要插入到流中的任何内容。或者,如果您只打算将内容插入函数中的流中,则直接不要插入函数的返回值:

当我们解决所有这三件事时,我们最终会得到

car.print(os);

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

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