如何在C++中将 cin 设置为类的成员函数?
How to set cin to a member function of a class in C++?
我正在制作一个小型主机游戏,我有一个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
变量中的值,然后调用类Player
的setName
方法:
cin>>name;
the_player.setName(name);
相关文章:
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 将公共但非静态的成员函数与ALGLIB集成
- 使用指向成员的指针将成员函数作为参数传递
- 将重载的成员函数传递给函数模板
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 如何在C++中使用非静态成员函数作为回调函数
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 关联容器的下界复杂性:成员函数与非成员函数
- 在 C++ 中用派生类型重写成员函数
- 链表的泛型函数remove()与成员函数remove)
- 如何将lambda作为模板类的成员函数参数
- constexpr构造函数需要常量成员函数时出现问题
- 将自由函数绑定为类成员函数
- 区分非成员函数和头文件中的成员函数
- 如何从子成员函数修改父公共成员变量
- 保留对其他类的成员函数的引用
- 在运算符重载定义中使用成员函数(const错误)
- 内联如何影响模块接口中的成员函数
- 将成员函数指针作为参数传递给模板方法