customer.h
C/C++ code
#ifndef _CUSTOMER_H
#define _CUSTOMER_H
#include <QString>
#include <QTextStream>
#include <QObject>
class Customer:public QObject
{
Q_OBJECT 学校运动会闭幕词 public:
explicit Customer(const QString &name);
QString toString() const;
friend QTextStream& operator << (QTextStream &out, const Customer &c);
};
#endif
customer.cpp
C/C++ code
#include "customer.h"
#include "customer.h"
Customer::Customer(const QString &name)
{
setObjectName(name);
}
QString Customer:: toString() const
{
QString retval = QString("Student ") + objectName();
return retval;
}
QTextStream& Customer::operator << (QTextStream &out, const Customer &c)
{
out << c.toString() ;
return out;
}
main.cpp
C/C++ code
#include <QApplication>
#include <QList>
#include <QDebug>
#include "customer.h"
int main()
{
QObject root;
Customer *name1 = new Customer("a");
name1->setParent(&root);
Customer *name2 = new Customer("b");
name2->setParent(&root);
QObject *name3 = new QObject;
name3->setObjectName("c");
name3->setParent(&root);
QList<Customer *> list = root.findChildren<Customer*>();
foreach(const Customer *current ,list)
{
qDebug() << current->toString() << " ";
}
return 0;
}大家看头文件 我把输出操作符放类中友元访问 报错: 错误:C2039: “<<”: 不是“Customer”的成员 为什么会报错呢? 如果把这个函数去掉friend 放类外 实现文件去掉Customer:: 编译就通过 我记得在C++环境下输出操作符重载可以作为友元放在类中的。。。。 为什么会这样呢?
QTextStream& Customer::operator << (QTextStream &out, const Customer &c)
{
out << c.toString() ;
return out;
}
啊~你的实现表示的是在Customer这类里的嘛。。。