【发布时间】:2014-06-05 22:36:44
【问题描述】:
我不知道下面的代码有多少与问题相关,但我有一个包含三个数据成员(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() 函数中永久更改??
【问题讨论】:
-
在 C++ 中,它们被称为成员函数,而不是方法。
-
最好不要贴sn-ps,而是构造一个testcase,这样我们可以自己重现问题,玩一玩。这实际上是调试的关键部分,所以在发布之前这样做。 sscce.org 老实说,我希望有人在 SO 上工作了两年并发布了 40 多个问题,现在知道这一点。
-
如果真的按照您的建议,说明的顺序没有任何问题。您是否省略了其他相关代码?你最后一次清理和重建是什么时候?你能告诉我们对象是如何实例化和访问的吗?
-
对象是如何被实例化然后被使用的?我在黑暗中的镜头是您实例化的变量与您正在打印的变量不同。尝试在两个打印输出中打印出
this指针,以确保它是同一个对象。 -
@LightnessRacesinOrbit 谢谢你的链接,我会读一读。我同意你的看法……我想我们最终都会学到这一课,现在是我的时候了。对不起那些家伙。