在C++中,为了避免将不会变化的字符串字面量复制到类字符串数据成员中,可以使用指针或者引用来存储字符串字面量的地址。以下是示例代码:
#include
#include
class MyClass {
private:
const char* strPtr; // 使用指针存储字符串字面量的地址
public:
MyClass(const char* str) : strPtr(str) {}
void printString() {
std::cout << strPtr << std::endl;
}
};
int main() {
MyClass obj("Hello, World!"); // 传递字符串字面量给构造函数
obj.printString(); // 输出:Hello, World!
return 0;
}
在上述示例中,我们使用const char*
类型的数据成员strPtr
来存储字符串字面量的地址。在构造函数中,我们将字符串字面量的地址传递给strPtr
。通过这种方式,我们避免了将字符串字面量复制到类数据成员中的操作。在printString()
函数中,我们可以直接输出strPtr
指向的字符串。
请注意,如果需要在类中存储可变的字符串,或者需要在类中对字符串进行修改操作,那么使用指针存储字符串字面量的地址可能不太合适,可以考虑使用std::string
类来管理字符串。