我正在创建一个快速游戏,我使用了一个不同的类文件来输入玩家名称。我一直得到指定的错误:
使用"&"为成员创建指针
当我试图从main调用函数时。
函数getPlayerOne
和getPlayerTwo
是公共函数。我想这是因为我正在更改player1
值,所以我需要一个指针,但当我尝试添加指针时,它会给我同样的错误。
如何使用指针编辑字符串的值?
main:
#include <iostream>
#include <string>
//Included Header Files
#include "Player.h"
using namespace std;
int main() {
Player players;
cout << players.getPlayerOne << endl;
cout << players.getPlayerTwo << endl;
}
Player.h:
#pragma once
#include <iostream>
#include <string>
using namespace std;
class Player
{
public:
//Initialize player1
void getPlayerOne(string &playerOne);
void getPlayerTwo(string &playerTwo);
Player();
private:
//Players
string player1;
string player2;
};
播放器.cpp
#include "Player.h"
Player::Player()
{
}
void Player::getPlayerOne(string &playerOne) {
cout << "Enter player 1 name: n";
cin >> playerOne;
cout << playerOne << " is a great name!n";
player1 = playerOne;
}
void Player::getPlayerTwo(string &playerTwo) {
cout << "Enter player 2 name: n";
cin >> playerTwo;
cout << playerTwo << " is a great name!n";
player2 = playerTwo;
}
我可能只是把Player
代码放在主代码中,因为它太小了,但我认为当(最终)我可以用更多字符编程文件时,最好有单独的类。
您有两个名为getPlayerX(string & name)
的函数,没有返回任何内容:我认为你在什么是"getter"one_answers"setter"方面犯了一个错误。
您希望std::cout
GET为字符串,然后使函数getPlayerX()
类似于GETTER:
std::string getPlayerX() const noexcept;
如果要设置您的数据,请创建SETTER:
void setPlayerX(const std::string & name);
记住,你使用的功能是这样的:
Type_you_want_to_get Name_of_the_function ([const] type_of_argument [&] var_name)
void"表示"不返回任何内容。
我不得不用参数调用函数,因为它们中已经有了cout和cin语句。愚蠢的错误。
string player1;
string player2;
int main() {
Player players;
players.getPlayerOne(player1);
players.getPlayerTwo(player2);
}