【发布时间】:2015-07-26 23:34:46
【问题描述】:
如何将指向某人配偶姓名的指针存储为该人类的私有成员?
例如,假设我有以下代码:
#include <iostream>
#include <list>
using namespace std;
class person
{
private:
string name;
string *spouse;
public:
void setName(string tempName) { name = tempName; }
void setSpouse(string &tempSpouse) { spouse = &tempSpouse; } // ERROR HERE?
string getName() { return name; }
string getSpouse() { return spouse; } // ERROR HERE?
};
int main()
{
person entry;
list<person> personList;
list<person>::iterator itr1, itr2;
/* Adding two people/nodes to the linked list. */
entry.setName("John Doe");
personList.push_back(entry);
entry.setName("Tina Doe");
personList.push_back(entry);
/* Attempting to assign Tina Doe as John Doe's spouse. */
for (itr1 = personList.begin(); itr1 != personList.end(); itr1++)
{
if (itr1->getName() == "John Doe")
{
for (itr2 = personList.begin(); itr2 != personList.end(); itr2++)
{
if (itr2->getName() == "Tina Doe")
{
itr1->setSpouse(itr2->getName()); // ERROR HERE?
}
}
}
}
/* Displaying all Names with Spouses afterwards. */
for (itr1 = personList.begin(); itr1 != personList.end(); itr1++)
{
cout << "Name: " << itr1->getName() << " | Spouse: " << itr1->getSpouse() << endl;
}
return 0;
}
我无法将配偶姓名的地址分配给班级中的指针成员。我已经在 cmets 中指出了我认为可能存在错误的位置。
您可以在这里查看代码和错误:https://ideone.com/4CXFnt
任何帮助将不胜感激。谢谢。
【问题讨论】:
-
如果有其他我忽略的信息,请告诉我,我会立即编辑这篇文章。谢谢。
-
考虑将
std::list替换为std::vector。std::list是一个双向链表,只有在真正必要时才使用它(中间经常插入和删除)。对于任何其他用途,它很慢。默认使用vector。 -
@IlyaPopov 不幸的是,对于这个特定的程序,使用向量是不可能的。必须是链表,配偶成员必须包含指向配偶姓名记录的指针。
-
啊,我明白了。如果它必须包含一个指向配偶的指针,那么列表确实是一个合适的选择。
-
@IlyaPopov 关于如何解决我的代码出现的错误,您还有其他建议吗?
标签: c++ pointers stl compiler-errors linked-list