问题
I am making a small console game and I have a player
class with private integers for the stats and a private string for the name. What I want to do is to ask the user for their name, and store that into the private name
variable in the player
class. I got an error stating:
error: no match for 'operator>>'
(operand types are 'std::istream {aka std::basic_istream<char>}' and 'void')
Here is my code:
main.cpp
#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;
}
Player.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
Player.cpp
#include "Player.h"
#include <string>
#include <iostream>
Player::Player() {
}
void Player::setName(string setAlias) {
name = setAlias;
}
string Player::getName() {
return name;
}
回答1:
The return type for the setName
function is void
, not a string
. So you have to store first the variable in a string
, and then pass it to the function.
#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;
}
回答2:
If you surely want use function, should return object reference.
string& Player::getNamePtr() {
return name;
}
cin >> the_player.getNamePtr();
回答3:
Firstly, try to get the value in the name
variable from the user and then call the setName
method of the class Player
:
cin>>name;
the_player.setName(name);
来源:https://stackoverflow.com/questions/51959328/how-to-set-cin-to-a-member-function-of-a-class-in-c