【发布时间】:2015-08-19 16:03:36
【问题描述】:
我的类和成员函数目前存在一些问题,特别是从 setter 函数获取用户输入,然后从 print info 函数显示该信息。我有一个单独的函数,允许用户输入有关字符的信息,然后是一个 getter 函数,然后用于打印出用户输入的信息。当我第一次运行它时,我遇到了需要使用指向成员函数的指针的错误,我在打印信息函数中添加了 &Character::GetCharacterName 和其他。现在,当我通过我的主函数运行程序时(我没有包含它,因为它只是调用所有函数)我的程序将运行,但无论用户输入什么,所有值都设置为 1。我知道它与指针有关,因此对于正确设置它以便返回用户输入的值的任何帮助将不胜感激。谢谢
Character.h file
class Character
{
public:
Character();
void SetCharacterName();
void SetCharacterType();
void SetCharacterLevel();
string GetCharacterName();
string GetCharacterType();
double GetCharacterLevel();
void PrintInfo();
private:
string CharacterName;
string CharacterType;
double CharacterLevel;
};
Character.cpp file
Character::Character()
{
CharacterLevel = 1.0;
}
void Character::SetCharacterName()
{
cout << "\nWhat is the character's name? ";
cin >> CharacterName;
}
void Character::SetCharacterType()
{
cout << "\nWhat is the character's type? ";
cin >> CharacterType;
}
void Character::SetCharacterLevel()
{
cout << "\nWhat is the character's level? ";
cin >> CharacterLevel;
}
string Character::GetCharacterName()
{
return CharacterName;
}
string Character::GetCharacterType()
{
return CharacterType;
}
double Character::GetCharacterLevel()
{
return CharacterLevel;
}
void Character::PrintInfo()
{
system("pause");
system("cls");
cout << "\nCharacter name is " << &Character::GetCharacterName << ".\n";
cout << "\nCharacter type is " << &Character::GetCharacterType << ".\n";
cout << "\nCharacter level is " << &Character::GetCharacterLevel << ".\n";
}
【问题讨论】:
-
虽然 FPK 的回答是对的,但没有必要使用 getter,因为
PrintInfo()可以直接访问属性,所以你可以简单地使用std::cout << CharacterName << std::endl。
标签: c++ function class pointers member