c++ - 如何让一个类作为 printf_s/sprintf_s 的字符串?

标签 c++ c printf

我正在尝试创建一个类,比如说 MyClass,在以下条件下工作:

MyClass name = "everyone";   // Assigns "everyone" into a local string variable.
printf_s("Hello %s!", name); // Should output "Hello everyone!" without the quotes.

我试过重载 operator const char*() 以及 operator char*() 但似乎都没有成功。

最佳答案

如果用 operator const char* 重载它,你可以显式地转换它:

MyClass name = "everyone";
printf_s("Hello %s!", (const char*)name);
// prints "Hello everyone!"

然后它会正常运行。因为printf,它不能隐式工作可以在第一个参数之后采用任何类型的参数,因此编译器不知道要尝试将其转换为什么。

当然,这假设 operator const char*你的类返回 C 风格的字符串 everyone .

正如 Tomalak Geret'kal 在评论中指出的那样,让您的类隐式转换为 const char*可能会导致很多问题,因为它可以在您不知情/不希望的情况下转换自己。

正如 Kerrek SB 也指出的那样,让您的类(class)与 printf 兼容可能不值得。 ,因为这毕竟是 C++。写一个 operator<< 会更好ostream& 过载小号:

ostream& operator<<(ostream& rhs, const MyClass& c) {
    rhs << c.name; // assuming the argument to the constructor
                   // is stored in the member variable name

    return rhs;
}

MyClass name = "everyone";
cout << "Hello " << name << '!';

// prints "Hello everyone!"

关于c++ - 如何让一个类作为 printf_s/sprintf_s 的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7237234/

相关文章:

c - 执行 C 程序时创建了多少个文件?

c - 在 printf 中显示字符串而不是数字 (C)

Java - 为什么我会收到 UnknownFormatConversionException?

c++ - 具有许多基本情况的模板递归

c++ - 高效编辑图像中的像素

c++ - 从 Vulkan 中的 R16_UINT-3D 纹理在片段着色器中采样值

c - C 中判断指针是否属于集合的最快方法是什么?

c++ - 将对象指针作为成员函数 : is it standard? 的第一个参数传递

将字符数组的一部分复制到C中的另一个数组

c - 简单的 C 结构 : Trouble storing a char * [] into a struct in C. 不兼容的类型