从另一个类方法

时间:2015-06-30 05:38:36

标签: c++ linked-list

我有一个iObj类,在其构造函数中包含两个参数,然后将该对象传递给另一个从(iObj)获取对象并将其存储在链接列表(List)中的类(存储)的另一个方法(Add)。 链接列表有自己的类。

当我像这样运行main时

  Store st;
  st.Add(iObj(Britain", 1));
  st.Add(iObj(Germany", 0.01));
  st.Add(iObj(Bhutan", 10));

  st.PrintStore();

屏幕上没有显示任何内容。

列出实施。

List::List()
{
    head = NULL;
}

void List::insert(iObj* new_node)
{
    new_node->next = head;
    head = new_node;
}

void List::Print()
{
    iObj* temp = head;
    while (temp != NULL)
    {
        std::cout << temp->GetValue()) << "\t";
        temp = temp->next;
    }
}

iObj类实现。

class iObj
{
    public:
          iObj(char const* first_name, double value);
           char GetValue()
       // ~iObj();
       // copy constructor
       // copy assignment operator
        friend class LinkedList;

    private:
        char*   first_name;
        double  value;
        iObj* next;
};

iObj::iObj(char const* first_name, double value) : first_name(new char[strlen(first_name) + 1]), value(value), next(NULL)
{
    strcpy_s(this->first_name, (strlen(first_name) + 1), first_name);
}

char* iObj::GetValue()
{
    return first_name;
}

商店实施。这是iObj存储到链接列表(列表)

的地方
void store::Add(iObj& UserIObj)
{
    List LL;
    iObj* s1 = new iObj("China", 3.5);
    LL.insert(s1);
}

1 个答案:

答案 0 :(得分:3)

当然,您每次进入store::Add时都会创建一个新列表。所以,你只是将元素添加到堆栈上的列表然后销毁它。

您需要将List LL作为store的成员而不是局部变量。

(除非List有静态成员,但我没有假设)。