如何在 C++ 中将 cin 设置为 class 的成员函数?

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

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

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 函数的 return 类型是 void,而不是 string。所以你必须首先将变量存储在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;
}

首先尝试从用户获取name变量中的值,然后调用classPlayersetName方法:

cin>>name;
the_player.setName(name);

如果你确定要使用函数,应该return对象引用。

string& Player::getNamePtr() {
return name;
}

cin >> the_player.getNamePtr();