Cannot pass object of non-trivial type ‘std::string‘ (aka ‘basic_string<char>‘) through variadic fun

1 篇文章 0 订阅

使用c++的时候出现的异常

Cannot pass object of non-trivial type ‘std::string’ (aka ‘basic_string’) through variadic function; call will abort at runtime

这个错误提示表明,你正在尝试通过变参函数(如 printf 等)传递一个 std::string 对象,而这在 C++ 中是不允许的,因为 std::string 是一个非平凡类型(non-trivial type),它有自己的构造函数、析构函数和其他复杂的行为。

解决方法:

你需要将 std::string 转换为 C 风格的字符串(即 const char)来传递给变参函数。*

例如,假设你正在调用 printf 来输出一个 std::string:


#include <string> 

#include <cstdio> 

  

int main() { 

    std::string myString = "Hello, World!"; 

     

    // 使用c_str()方法将std::string转换为C风格的字符串 

    printf("My string is: %s\n", myString.c_str()); 

     

    return 0; 

} 

c_str() 方法将 std::string 转换为 const char*,这是一个指向 C 风格字符串的指针,这样就可以安全地传递给变参函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值