QT中使用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);
}
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)
{
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我所知,“adda”功能不会影响任何东西。它不返回任何内容,并且仅对“I”进行操作,“I”在“adda”完成时被删除。
我相信您可以使用友元函数的一个示例是,如果您将“adda”声明/定义为:
... 尽管在这种特殊情况下,没有理由不让“adda”成为 InBoxTab 的成员。
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:
... Although in that particular case there is no reason not to make 'adda' a member of the InBoxTab instead.
在函数
adda()
中,创建了一个名为I
的新对象。因此,构造函数被调用,构造函数又再次调用adda()
,并且该过程继续进行。我看到无限递归,这就是问题所在。编辑:
In the function
adda()
, a new object calledI
is created. So, constructor is called and constructor inturn calls againadda()
and the process goes on . I see an infinite recursion which is the problem.Edit: