c++数据成员在单独的成员函数中定义后返回垃圾
C++ data members return garbage after being defined in a separate member function
我不知道下面的代码有多少与问题相关,但是我有一个派生类,其中有三个数据成员(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()
函数永久改变?
错误在您遗漏的部分。你所拥有的没有什么错,事实上,如果我实现你在评论中所说的,那么我得到预期的输出:
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;
}
相关文章:
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- flutter:即使shouldRepaint()返回true,自定义画家也不会重新绘制
- 编译时的 CImg 库返回对"__imp_SetDIBitsToDevice"的未定义引用
- 通过 NIF 从C++返回自定义数据结构
- 如何在C++中允许成员函数的自定义返回类型进行类型擦除?
- 如何在 Cython 中定义返回 cpp 定义类型的函数?
- 我应该如何定义返回指针的函数?(引用指针与指针指针)
- 是否可以为类设置自定义返回类型
- 具有自定义返回类型和"false"返回条件的函数?
- C :不同类型的模板功能(方法)的自定义返回值
- 在派生类中定义自定义返回类型的受保护方法
- 声明/定义返回具有自动返回类型的 valarray 的函数时的隔离错误
- 嵌套类 - 定义返回对象的函数
- 有没有办法在C++函数体内定义返回类型
- 自定义返回类型声明
- 带有自定义返回值的seresult
- 具有自定义返回类型的全局命名空间中的友元函数
- 类型定义 返回模板参数的成员函数的类型
- 让宏定义返回函数的值是不好的做法吗?