我只是想将播放器数据存储在它自己的类中,并使用一个函数在类中显示数据。
我将所有播放器数据都存储在 Player
类中,将私有(private)变量输出到 main 中没有问题,但我创建了一个函数来获取所有播放器数据并显示它。
Player
类中的 getPInfo
函数应该从类中获取名称并将其放入 中的
函数并显示。但正如您想象的那样,事实并非如此。 getPInfo 函数未能成功将名称值传递给 getPlayer 函数。pName
字符串中getPlayer
请记住,我不是 C++ 专家,所以请让您的回答平易近人。
#include "stdafx.h"
#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::string;
class Player {
public:
Player() {
name = "?";
}
void getPInfo(string x) {
x = name;
}
void setName(string x) {
name = x;
}
private:
string name;
};
void getPlayer() {
string pName;
Player player;
player.getPInfo(pName);
cout << "Name = " << pName << endl;
}
int main()
{
string str;
cout << "What is your name?\n" << endl;
cin >> str;
Player pObj;
pObj.setName(str);
getPlayer();
}
最佳答案
修复它并使它更像 c++:
#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::string;
class Player {
public:
Player()
: name("?")
{}
const string& getPInfo() const{
return name;
}
void setName(const string& x) {
name = x;
}
private:
string name;
};
void getPlayer(const Player& player) {
string pName;
pName = player.getPInfo();
cout << "Name = " << pName << endl;
}
int main()
{
string str;
cout << "What is your name?\n" << endl;
cin >> str;
Player pObj;
pObj.setName(str);
getPlayer(pObj);
}
关于c++ - 将类中私有(private)变量的值传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46315721/