我想从对象外部操作链接列表,但它不像我想的那样工作。
情况是这样的:我有一个对象,它有一个基类的指针,指向第一个条目,以标记链表的开头。
class theObject {
public:
theObject() : mFirstEntry(0), mLastEntry(0) {}
~theObject() {}
template<class T>
void addEntry(const std::string &blah, const std::string &blub, const T &hui)
{
child<T> *newEntry = new child<T>(blah, blub, hui);
if (mFirstEntry) {
mLastEntry->setNext(newEntry);
mLastEntry = newEntry;
}
else {
mFirstEntry = newEntry;
mLastEntry = newEntry;
}
}
base * getFirstEntry() const
{
return mFirstEntry;
}
void printEntrys() const
{
base *data = mFirstEntry;
while(data) {
std::cout << data->getBlah() << data->getBlub() << std::endl;
data = data->getNext();
}
}
private:
base *mFirstEntry;
base *mLastEntry;
};
class base {
public:
base() : mBlah(""), mBlub(""), mNext(0) {}
base(const std::string &blah, const std::string &blub) : mBlah(blah), mBlub(blub), mNext(0) {}
virtual ~base()
{
if (mNext) {
delete mNext;
}
}
void setNext(base *next)
{
mNext = next;
}
base * getNext() const
{
return mNext;
}
std::string getBlah() const
{
return mBlah;
}
std::string getBlub() const
{
return mBlub;
}
protected:
std::string mBlah;
std::string mBlub;
base *mNext;
};
链表的每个条目都是子类型,它是一个模板并继承了基类。
template<class T>
class child : public base {
public:
inline child(const std::string &blah, const std::string &blub, const T &hui, base *next = 0) : mHui(hui), base(blah, blub)
{
if(next) {
mNext = next;
}
}
inline child(const child &r)
{
*this = r;
}
inline const child & operator = (const child &r)
{
if (this == &r) return *this;
mBlah = r.mBlah;
mBlub = r.mBlub;
mNext = r.mNext;
mHui = r.mHui;
return *this;
}
inline const T getData() const
{
return mHui;
}
protected:
T mHui;
};
现在我用几个条目填充对象
int main(int argc, char* argv[])
{
theObject data;
int a(0), b(1), c(2), d(3);
const std::string blah("blah"), blub("blub");
data.addEntry(blah, blub, a);
data.addEntry(blah, blub, b);
data.addEntry(blah, blub, c);
data.addEntry(blah, blub, d);
std::cout << "Original entries" << std::endl;
data.printEntrys();
然后我想maipulate链表
base *stuff = data.getFirstEntry();
std::cout << "Changed in stuff list" << std::endl;
while(stuff) {
stuff = new child<double>("noBlah", "noBlub", 3.14, stuff->getNext());
std::cout << stuff->getBlah() << stuff->getBlub() << std::endl;
stuff = stuff->getNext();
}
并希望操纵原件……但它接缝我只操纵了一个副本
std::cout << "linked list in data object should now be stuff list" << std::endl;
data.printEntrys();
return 0;
}
有没有人知道为什么它不工作?getFirstEntry() 返回一个指针,所以我想我会操纵它指向的对象。
最好的问候,本