我正在尝试通过使用指针来创建C 中的简单家谱,以便输入该名称的字符串,然后在代码中逐步保存的名称。
例如,该程序从一个未知的位置开始,并提示用户输入当前位置的名称,请移至爸爸的位置,移至妈妈的位置,或者回到起始人(首先(注册的人(。这就是我到目前为止所拥有的:
#include <iostream>
#include <cstdlib>
using namespace std;
class person
{
public:
person* mom;
person* dad;
string name;
person();
~person();
person(string n);
};
person::person()
{
mom = nullptr;
dad = nullptr;
name = "Unknown";
}
person::~person()
{
//delete any dynamic memory if needed
}
person::person(string n)
{
name = n;
}
int main()
{
string inputName;
person current;
person *pointer; //I know I'll probably need to use a class pointer
//in some manner to keep track of the current pointer, but how?
//also, how to turn private variables in person into public
//while still being able to use them indirectly in main, if possible?
char choice;
do {
cout << "You are currently at: " << current.name << endl;
cout << "Your mom is: ";
if(current.mom == nullptr)
{
cout << "???" << endl;
}
else
{
cout << current.mom;
}
cout << "Your dad is: ";
if(current.dad == nullptr)
{
cout << "???" << endl;
}
else
{
cout << current.dad;
}
cout << "Give name, go to mom, go to dad, back to start, or quit?" << endl;
cin >> choice;
if (choice == 'g')
{
cout << "What name (single word)?" << endl;
cin >> inputName;
current.name = inputName;
}
else if (choice == 'm')
{
//go to mom spot
}
else if (choice == 'd')
{
//go to dad spot
}
else if (choice == 'b')
{
//go to first registered name
}
}
while (choice == 'g' || choice == 'm' || choice == 'd' || choice == 'b');
//else quit
return 0;
}
目前,我的代码非常草率,因为我是C 的完整初学者,并且仅在一周前就开始了。我知道公共变量是一种非常糟糕的做法,但是我真的不知道如何在Main内使用私人变量。对如何组织我的指针或如何使私人变量在MAIN中起作用的任何帮助将不胜感激。
您正确地声明并定义了班级的公共成员,以实现您不需要更改太多的私人成员。
在您的班级定义下,您只需要包括一个"私人:"部分。您在那里声明您的私人变量或功能,以及在公共标题下的这些变量的Getters和Setter。
所以你的
class person
{
public:
person* mom;
person* dad;
string name;
person();
~person();
person(string n);
};
变成
class person
{
public:
person();
~person();
person(string n);
void setName(string);
person* getMom();
person* getDad();
string getName();
private:
person* mom;
person* dad;
string name;
};
请注意,声明函数时,您无需提供任何参数变量的名称。这是完全可选的;编译器只需要知道什么类型的变量。
然后,就像您如何定义构造函数和驱动器一样,您定义了刚刚声明的getters和setter。
...
person::person(string n)
{
name = n;
}
void person::setName(string name)
{
this->name = name;
}
person* person::getMom()
{
return mom;
}
person* person::getDad()
{
return dad;
}
string person::getName()
{
return name;
}
int main()
...
这种格式基本上与要将人员类别分为自己的标题(.h(和cpp(.cpp(文件相同。
,要访问私人会员,您只需要致电您刚创建的getters或setter。所以,
cout << "You are currently at: " << current.name << endl;
变成
cout << "You are currently at: " << current.getName() << endl;
希望这是有道理的。
ps:如果您使用C 的字符串类,则可能需要#include <string>
pps:始终将您所做的任何班级的首字母都大写。就是这样脱颖而出。Person
代替person
。