喜欢标题。
我的目标是在不重新创建对象的情况下获取对象, 显然我可以使用指针,但
1)我喜欢保留工厂对象,数据库处理程序等的指针
2)我想学习一些东西而不是简单的方法
所以代码和错误都在底部,感谢您的时间和建议:)
代码中的某处
QTcpSocket* socket = (QTcpSocket*)this->sender();
Request request(socket);
Response response(request, this->managerFactory);
response.h
#ifndef RESPONSE_H
#define RESPONSE_H
#include <QString>
#include "Request.h"
#include "../manager/ManagerFactory.h"
class Response {
public:
Response(const Request &request, ManagerFactory *managerFactory);
QString getValue();
private:
QString generateJsonHeader();
Request &request;
ManagerFactory *managerFactory;
};
#endif /* RESPONSE_H */
resonse.cpp
#include "Response.h"
Response::Response(const Request &request, ManagerFactory *managerFactory)
{
this->request = request;
this->managerFactory = managerFactory;
}
request.h
#ifndef REQUEST_H
#define REQUEST_H
#include <QTcpSocket>
#include <QStringList>
#include <QString>
#include <QMap>
class Request {
public:
Request(QTcpSocket* socket);
bool hasParameter(QString paramName);
QString getParameter(QString paramName);
private:
void loadParameters(QTcpSocket* socket);
QMap<QString, QString> parameters;
};
#endif /* REQUEST_H */
request.cpp
#include "Request.h"
Request::Request(QTcpSocket* socket)
{
this->loadParameters(socket);
}
这是我面临的错误
source/server/Response.cpp: In constructor ‘Response::Response(const Request&, ManagerFactory*)’:
source/server/Response.cpp:3:1: error: uninitialized reference member ‘Response::request’ [-fpermissive]
make[2]: *** [build/Release/GNU-Linux-x86/Response.o] Error 1
答案 0 :(得分:1)
您正尝试对引用成员变量进行赋值,而不是在初始化列表中初始化它。这是非法的,这就是你遇到错误的原因。
您应该在标题中编写以下构造函数:
class Request;
// ...
class Response {
public:
Response(Request &r) : request(r) {}
// ...
private:
Request &request;
};
虽然,您可能希望考虑使用指针而不是引用成员变量。