gpt4 book ai didi

C++ noob - 类作用域

转载 作者:IT王子 更新时间:2023-10-29 06:03:12 26 4
gpt4 key购买 nike

我有以下 C++ 类:

class Eamorr {
public:
redispp::Connection conn;

Eamorr(string& home, string& uuid)
{
//redispp::Connection conn("127.0.0.1", "6379", "password", false); //this works, but is out of scope in put()...
conn=new redispp::Connection("127.0.0.1", "6379", "password", false); //this doesn't work ;(
}
put(){
conn.set("hello", "world");
}
...
}

如您所见,我希望 conn 在构造函数中初始化并在 put() 方法中可用。

我该怎么做?

非常感谢,

最佳答案

这就是成员初始化列表的用途:

 Eamorr(string& home, string& uuid) 
: conn("127.0.0.1", "6379", "password", false)
{
//constructor body!
}

: 之后的语法(包括这个)构成了 member-initiazation-list。您可以在这里初始化成员,每个成员用逗号分隔。

这是一个详细的例子:

struct A
{
int n;
std::string s;
B *pB;

A() : n(100), s("some string"), pB(new B(n, s))
{
//ctor-body!
}
};

有关更多信息,请参阅这些:

关于C++ noob - 类作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8166961/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com