我不知道下面的代码中有多少与这个问题相关,但是我有一个派生类,它有三个数据成员(loc、remote_host和remote_port)。它们在类的头文件中声明,并在Initialize()成员函数中定义。但是,当HandleRequest()函数试图访问它们时,remote_host和remote_port分别返回垃圾和0;loc按预期返回"/proxy"。有人能指出显而易见的吗?我在这里迷路了。
// in response_handler.hh
class ResponseHandlerInterface {
public:
virtual bool Initialize(const NginxConfig& config) = 0;
virtual bool HandleRequest(const std::string& request, std::string* response) = 0;
};
// in ProxyHandler.hh
class ProxyHandler : public ResponseHandlerInterface {
public:
std::string loc, remote_host;
int remote_port;
bool Initialize(const NginxConfig&);
bool HandleRequest(const std::string&, std::string*);
};
// in ProxyHandler.cc
bool ProxyHandler::Initialize(const NginxConfig &config) {
loc = "/proxy";
remote_host = "digboston.com";
remote_port = 80;
std::cout << "Values in Initialize():" << std::endl;
std::cout << loc << " " << remote_host << " " << remote_port << std::endl;
return true;
}
bool ProxyHandler::HandleRequest(const std::string &request, std::string *response) {
std::cout << "Values in HandleResponse():" << std::endl;
std::cout << loc << " " << remote_host << " " << remote_port << std::endl;
return true;
}
// in main.cc
// a new instance of ProxyHandler is created,
// Initialize() is called on the object,
// HandleRequest() is called on the object.这是输出:
>> ./runprogram
Values in Initialize():
/proxy digboston.com 80
Values in HandleResponse():
/proxy H?/P??P?? P??@ P??` P?? 0如您所见,loc保留了它的值。remote_host和remote_port保存它们初始化时的垃圾值。如何确保所有三个值都从Initialize()函数中永久更改??
发布于 2014-06-05 22:48:05
错误就在你遗漏的部分。您所拥有的没有什么问题,实际上,如果我实现了您在评论中所说的内容,那么我就得到了预期的输出:
Values in Initialize():
/proxy digboston.com 80
Values in HandleResponse():
/proxy digboston.com 80我的补充如下:
#include <iostream>
struct NginxConfig {};
// YOUR CODE GOES HERE
int main() {
ProxyHandler ph;
ph.Initialize(NginxConfig());
ph.HandleRequest(std::string(""), NULL);
return 0;
}https://stackoverflow.com/questions/24071329
复制相似问题