gpt4 book ai didi

c++ - 如何在 C++ 中使用运算符重载来显示类(游戏板)

转载 作者:行者123 更新时间:2023-11-28 07:16:37 25 4
gpt4 key购买 nike

我创建了一个 hexBoard 类,里面有一个数据结构来存储和显示游戏板

我已经成功地重载了 << 运算符,现在在创建实例后的 main 方法中,我可以通过编写 cout << hex 来简单地显示面板

 class hexBoard
{
vector<vector<bool>> board;
.....
void display();

}

ostream& operator<< ( ostream& out , hexBoard& hex )
{
.......
return out;
}

int main()
{
hexBoard hex;
cout<<hex;
}

一切正常

现在我的问题是什么时候试图通过编写从成员函数 display() 内部显示相同的板

计算<<*这个

我收到类似没有匹配类型的错误

 hexBoard::display()
{
cout<<*this;
}
int main()
{
hexBoard hex;
hex.display();
}

请告诉我哪里出错了,正确的做法是什么

最佳答案

因为你没有重载this.operator<<(ostream&, hexBoard&) .记住,operator<<()在类外重载,因为它的第一个参数永远不能隐式为 this .所以你重载了operator<<(ostream&, hexBoard&)但在你的方法内 display()它正在寻找 this.operator<<(ostream&, hexBoard&)这永远不可能。

关于c++ - 如何在 C++ 中使用运算符重载来显示类(游戏板),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20122441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com