如何在C ++中将cin设置为类的成员函数? [英] How to set cin to a member function of a class in C++?

查看:34
本文介绍了如何在C ++中将cin设置为类的成员函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个小型的主机游戏,我有一个 player 类,其中的私有整数表示统计数据,私有字符串表示名称.我想要做的是询问用户的姓名,并将其存储到 player 类中的私有 name 变量中.我收到一条错误消息:

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')

这是我的代码:

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;
}

推荐答案

setName 函数的返回类型为 void ,而不是 string .因此,您必须首先将变量存储在 string 中,然后将其传递给函数.

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;
}

这篇关于如何在C ++中将cin设置为类的成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆