gpt4 book ai didi

c++ - C++运算符重载编译错误

转载 作者:太空宇宙 更新时间:2023-11-04 15:03:44 24 4
gpt4 key购买 nike

我正在尝试编写一个程序来模拟在 C++ 中玩 Battleship

#include <iostream>
#include <vector>

class Ship {
public:
Ship();
Ship operator<<(const Ship&);
private:
int x = 0;
int y = 0;
std::vector<std::pair<int, int>> ship_loc; //Ship location
};

Ship::Ship() {
srand(time(NULL));
std::vector<std::pair<int, int>> ship_loc; //Ship location
for (int i = 0; i < 4; ++i) {
x = rand() % 20;
y = rand() % 20;
std::pair<int, int> coordinates = std::make_pair(x, y);
ship_loc.push_back(coordinates);
//ship_loc.push_back(std::pair<x, y>)
};
};

Ship operator<<(const Ship &s) {
std::cout << ship_loc[0] << ship_loc[1] << ship_loc[2] << ship_loc[3]
<< std::endl;
}

int main()
{
Ship first_ship;
std::cout << first_ship;
}

每当我尝试编译它时,它都会给我:

battleship.cpp:26:30: error: âShip operator<<(const Ship&)â must take exactly two           arguments
battleship.cpp: In function âint main()â:
battleship.cpp:34:25: error: cannot bind âstd::ostream {aka std::basic_ostream<char>}â lvalue to âstd::basic_ostream<char>&&â
In file included from /usr/include/c++/4.7/iostream:40:0,
from battleship.cpp:1:
/usr/include/c++/4.7/ostream:600:5: error: initializing argument 1 of âstd::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = Ship]â

显然还不是很有上课经验。完全没有。

最佳答案

您声明了 operator <<作为成员函数

Ship operator<<(const Ship&);

这意味着左操作数是类 Ship 的一个实例。所以它可以被称为

Ship a, b;

a << b;

但很明显你不想要这个。

如果要在输出流中输出类 Ship 的对象,则运算符必须是非成员函数。您可以将其定义为该类的友元函数。例如

class Ship {
public:
Ship();
friend std::ostream & operator <<( std::ostream &os, const Ship& );
private:
int x = 0;
int y = 0;
std::vector<std::pair<int, int>> ship_loc; //Ship location
};

然后你可以像下面这样定义它

std::ostream & operator <<( std::ostream &os, const Ship &s) 
{
os << "( " << s.ship_loc[0].first << ", " << s.ship_loc[0].second << " )"
<< ", ( " << s.ship_loc[1].first << ", " << s.ship_loc[1].second << " )"
<< ", ( " << <.ship_loc[2].first << ", " << s.ship_loc[3].second << " ) "
<< ", ( " << <.ship_loc[3].first << ", " << s.ship_loc[3].second << " ) "
<< std::endl;

return os;
}

此外,由于坐标数是固定的,因此无需使用 std::vector .改用 std::array<std::pair<int, int>, 4>

同时删除声明

std::vector<std::pair<int, int>> ship_loc;      //Ship location

来自构造函数。它是一个局部变量。您需要填写数据成员 ship_loc 而不是这个局部变量。

关于c++ - C++运算符重载编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22571215/

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