我正在制作一个小型控制台游戏,我有一个player类,其中包含用于统计数据的私有整数和用于名称的私有字符串。我想要做的是向用户询问他们的姓名,并将其存储到类中的私有name变量中player。我收到一个错误说明:
error: no match for 'operator>>'
(operand types are 'std::istream {aka std::basic_istream<char>}' and 'void')
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
主程序
#include "Player.h"
#include <iostream>
#include <string>
using namespace std;
int main() {
Player the_player;
string name;
cout << "You wake up in a cold sweat. Do you not remember anything \n";
cout << "Do you remember your name? \n";
cin >> the_player.setName(name);
cout << "Your name is: " << the_player.getName() << "?\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
播放器.h
#ifndef PLAYER_H
#define PLAYER_H
#include <string>
using namespace std;
class Player {
public:
Player();
void setName(string SetAlias);
string getName();
private:
string name;
};
#endif // PLAYER_H
Run Code Online (Sandbox Code Playgroud)
播放器.cpp
#include "Player.h"
#include <string>
#include <iostream>
Player::Player() {
}
void Player::setName(string setAlias) {
name = setAlias;
}
string Player::getName() {
return name;
}
Run Code Online (Sandbox Code Playgroud)
setName函数的返回类型是void,而不是string。因此,您必须首先将变量存储在 a 中string,然后将其传递给函数。
#include "Player.h"
#include <iostream>
#include <string>
using namespace std;
int main() {
Player the_player;
cout << "You wake up in a cold sweat. Do you not remember anything \n";
cout << "Do you remember your name? \n";
string name;
cin >> name;
the_player.setName(name);
cout << "Your name is: " << the_player.getName() << "?\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)