我看到一个C++代码,其中一个结构定义如下,带有奇怪的const char* const*
struct TestStruct {
const char* const* text;
void* data;
};
我需要使用上面的结构,并从函数中返回它的一个对象。但是,如何将text
变量初始化为常量字符串呢?此外,如何从调用方函数访问text
指向的字符串。
TestStruct TestFunction() {
TestStruct struct_obj;
// TODO: how to assign struct_obj.text
}
int main() {
TestStruct struct_obj = TestFunction();
// TODO: how to access struct_obj.text
}
常量是不可变的,因此不能分配给。它们只能初始化。要从函数返回这样的结构,可以使用聚合初始化(大括号初始化(。这个结构可以用任何字符**初始化,但访问它的只能从字符**中读取,不能修改它。
TestStruct TestFunction()
{
char** lines = new char*[2];
// Work with char** stored in lines
*(lines + 0) = new char[10];
*(lines + 1) = new char[20];
void* data = nullptr;
return TestStruct{ lines , data };
}
int main()
{
TestStruct my_struct = TestFunction();
// const char* const * means it's an immutable array of immutable CStrings
const char* line_one = *my_struct.text;
const char* line_two = *(my_struct.text + 1);
std::cout << line_one << std::endl;
std::cout << line_two << std::endl;
}
编辑:我决定进一步澄清一下。
"const char*const*";表示指向不可变字符串表的指针引用。这意味着引用本身可以随时更改为引用其他表。constness的最大级别是";const char*const*const"其读取为对不可变表的指针常量引用。指针常量引用意味着它在构造后不能指向任何其他表,如果它是结构的成员,则肯定需要对其进行聚合初始化,或者至少默认构造
您不能分配给常量变量,但您可以初始化这样的变量:
TestStruct TestFunction() {
static const char* string = "hello world";
TestStruct struct_obj = {
&string, // The text member
nullptr // The data member
}
return struct_obj;
}
TestStruct struct_obj;
...
(char*&)struct_obj.text = "works";