C++ 错误] 无法通过 '...' 传递非平凡可复制类型的对象 'std::string {aka class std::basic_string<char>}'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23450300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error] cannot pass objects of non-trivially-copyable type 'std::string {aka class std::basic_string<char>}' through '...'
提问by Jovica96
#include <stdio.h>
#include <string>
main()
{
int br_el[6],i;
std::string qr_naziv[6];
qr_naziv[0]="Bath tub";
qr_naziv[1]="Sink";
qr_naziv[2]="Washing machine";
qr_naziv[3]="Toilet";
qr_naziv[4]="Kitchen sink";
qr_naziv[5]="Dish washer";
for(i=0;i<6;i++)
{
printf("Input the number for %s =",qr_naziv[i]);\here lies the problem
scanf("%d",&br_el[i]);
}
This program is much longer, so I shortened it..
The thing is, I will enter numbers for array br_el[6]
, and I want it to show me for what object I am entering the number!
So when I try to compile it gives me the error:"[Error] cannot pass objects of non-trivially-copyable type 'std::string {aka class std::basic_string}' through '...'"
I tried to declare string qr_naziv[6];
but the string didn't even bold so it didn't work, so I googled and found out another way (std::string qr_naziv[6];
).
这个程序更长,所以我缩短了它。问题是,我将为 array 输入数字br_el[6]
,我希望它显示我输入的数字是什么对象!因此,当我尝试编译时,它给了我错误:“[Error] 无法通过 '...' 传递非平凡可复制类型 'std::string {aka class std::basic_string}' 的对象”我试图声明string qr_naziv[6];
但字符串甚至没有加粗所以它不起作用,所以我用谷歌搜索并找到了另一种方法(std::string qr_naziv[6];
)。
回答by Rubens
Well, C functions are not acquainted with C++ structures. You should do the following:
好吧,C 函数不熟悉 C++ 结构。您应该执行以下操作:
...
for(i = 0; i < 6; i++) {
printf("Input the number for %s =", qr_naziv[i].c_str());
scanf("%d", &br_el[i]);
}
...
Notice the call to the method c_str()
on the each std::string qr_naziv[i]
, which returns a const char *
to a null-terminated character array with data equivalent to those stored in the string-- a C-like string.
请注意c_str()
对 each方法的调用,该方法std::string qr_naziv[i]
将 a 返回const char *
到一个以空字符结尾的字符数组,其中的数据与存储在字符串中的数据等效——一个类似 C 的字符串。
Edit:
And, of course, since you're working with C++, the most appropriate to do is to use the stream operators insertion <<
and extraction >>
, as duly noted by @MatsPetersson. In your case, you could do the following modification:
编辑:当然,由于您使用的是 C++,因此最合适的做法是使用流操作符插入<<
和提取>>
,正如@MatsPetersson 所指出的那样。在您的情况下,您可以进行以下修改:
# include <iostream>
...
for(i = 0; i < 6; i++) {
std::cout << "Input the number for " << qr_naziv[i] << " =";
std::cin >> br_el[i];
}
...