首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++数据成员在单独的成员函数中定义后返回垃圾

C++数据成员在单独的成员函数中定义后返回垃圾
EN

Stack Overflow用户
提问于 2014-06-05 22:36:44
回答 1查看 349关注 0票数 0

我不知道下面的代码中有多少与这个问题相关,但是我有一个派生类,它有三个数据成员(locremote_hostremote_port)。它们在类的头文件中声明,并在Initialize()成员函数中定义。但是,当HandleRequest()函数试图访问它们时,remote_hostremote_port分别返回垃圾和0;loc按预期返回"/proxy"。有人能指出显而易见的吗?我在这里迷路了。

代码语言:javascript
复制
// 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.

这是输出:

代码语言:javascript
复制
>> ./runprogram

Values in Initialize():
/proxy digboston.com 80

Values in HandleResponse():
/proxy H?/P??P??    P??@    P??`    P?? 0

如您所见,loc保留了它的值。remote_hostremote_port保存它们初始化时的垃圾值。如何确保所有三个值都从Initialize()函数中永久更改??

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-06-05 22:48:05

错误就在你遗漏的部分。您所拥有的没有什么问题,实际上,如果我实现了您在评论中所说的内容,那么我就得到了预期的输出:

代码语言:javascript
复制
Values in Initialize():
/proxy digboston.com 80
Values in HandleResponse():
/proxy digboston.com 80

我的补充如下:

代码语言:javascript
复制
#include <iostream>

struct NginxConfig {};

// YOUR CODE GOES HERE

int main() {
  ProxyHandler ph;
  ph.Initialize(NginxConfig());
  ph.HandleRequest(std::string(""), NULL);
  return 0;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24071329

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档