How to set cin to a member function of a class in C++?

冷暖自知 提交于 2021-02-17 05:07:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!