Problem using Friend function in QT
I wish to add items in a ListWidget, which is a private member of a class, through a friend function. Actually, i am trying this sample snippet to use friend function for more classes to update their ListWidgets from a single function.
I need guidance in using friend function in my case.
Kindly forgive my ignorance on the topic, any help is appreciated.
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)
{
开发者_StackOverflow中文版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);
}
As far as I can see, the 'adda' function does not affect anything. It returns nothing, and only operates on 'I' which is deleted when 'adda' is finished.
An example of how I believe you could use a friend function would be if you declared/defined 'adda' as:
void adda(InBoxTab *I)
{
I->listWidget1->insertItem(1,QString("added frm fn"));
I->listWidget1->update();
}
... Although in that particular case there is no reason not to make 'adda' a member of the InBoxTab instead.
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
// ..
}
In the function adda()
, a new object called I
is created. So, constructor is called and constructor inturn calls again adda()
and the process goes on . I see an infinite recursion which is the problem.
Edit:
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.
精彩评论