在QT中使用Friend功能的问题

时间:2011-03-23 21:19:13

标签: c++ function qt4 friend

我希望通过友元函数在ListWidget中添加项,这是一个类的私有成员。实际上,我正在尝试使用此示例代码片段来使用友元函数来更多类来从单个函数更新其ListWidgets。

在我的情况下,我需要使用友方功能的指导。

请原谅我对这个话题的无知,感谢任何帮助。

    class InBoxTab : public QWidget
    {
    Q_OBJECT

    public:
        InBoxTab(QWidget *parent = 0);
       // InBoxTab();
        ~InBoxTab();

    public slots:
        void hello();
        friend void adda(); // friend function
    private:
        QListWidget* listWidget1; //data member accessed by friend function
    };



    void adda()
    {
        InBoxTab I;

        I.listWidget1->insertItem(1,QString("added frm fn"));

        I.listWidget1->update();
    }


InBoxTab::InBoxTab(QWidget *parent) :
        QWidget(parent)
{
        listWidget1 = new QListWidget(this);

        QListWidgetItem* item = new QListWidgetItem("Item 1 added frm tab1 ");

        listWidget1->addItem(item);
        adda();   // Call to friend function

        QVBoxLayout* layout = new QVBoxLayout(this);
        layout->addWidget(listWidget1);
        this->setLayout(layout);
}

2 个答案:

答案 0 :(得分:0)

void adda()
{
    InBoxTab I;

    I.listWidget1->insertItem(1,QString("added frm fn"));

    I.listWidget1->update();
}

InBoxTab::InBoxTab(QWidget *parent) :
          QWidget(parent)
{
    // ...

    adda();   // Call to friend function

    // ..
 }

在函数adda()中,创建了一个名为I的新对象。因此,构造函数被调用,构造函数inturn再次调用adda()并继续进行。我看到无限递归这就是问题所在。


修改

InBoxTab(QWidget *parent = 0); // Since parent is initialized to 0 if nothing 
                               // is passed to constructor up instantiation 

InBoxTab I; // Invokes the above constructor and an infinite recursion results.

答案 1 :(得分:0)

据我所知,'adda'功能不会影响任何东西。它什么都不返回,只对'I'进行操作,当'adda'完成时它被删除。

我认为你可以使用友方函数的一个例子就是你声明/定义'adda'为:

void adda(InBoxTab *I)
{
        I->listWidget1->insertItem(1,QString("added frm fn"));
        I->listWidget1->update();
}

...虽然在那种特殊情况下没有理由不让'adda'成为InBoxTab的成员。