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

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

本文关键字:成员 函数 设置 C++ 中将 cin      更新时间:2023-10-16

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

error: no match for 'operator>>'   
(operand types are 'std::istream {aka std::basic_istream<char>}' and 'void')

这是我的代码:

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

玩家.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

播放器.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中,然后将其传递给函数。

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

如果你肯定想要使用函数,应该返回对象引用。

string& Player::getNamePtr() {
return name;
}
cin >> the_player.getNamePtr();

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

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