#include<iostream>
#include <conio.h>
using namespace std;
struct book
{ int bookid;
char title[20];
float price;
}b2;
int main()
{
b2={100,"c++ by saurabh",105.2}; //values initialised during variable declaration
cout<<"\n"<<b2.bookid;
cout<<b2.title<<" "<<b2.price;
return 0;
getch();
}
以上代码显示输出错误,如下所示:
C:\ Users \ shandude \ Documents \ codeblock \ cprog \ struct2.cpp | 13 | error:不匹配&#39; operator =&#39; (操作数类型是&#39; book&#39;和&#39;&#39;)|
C:\ Users \ shandude \ Documents \ codeblock \ cprog \ struct2.cpp | 5 |注意:没有来自&#39;&#39;的参数1的已知转换到&#39; const book&amp;&#39; |
答案 0 :(得分:1)
您可以使用:
title
<强> PS 强>
我建议将成员变量std::string
更改为char
。使用struct book
{
int bookid;
std::string title;
float price;
};
数组来表示用户代码中的字符串在2017年是不合时宜的。
rfxtrx.service
答案 1 :(得分:0)
您正在做的不是初始化,而是赋值,因为b2
之前已经声明过。您需要在声明变量的位置进行初始化:
struct book
{ int bookid;
char title[20];
float price;
} b2 = {100,"c++ by saurabh",105.2}; //values initialised during variable declaration
int main()
{
cout<<"\n"<<b2.bookid;
cout<<b2.title<<" "<<b2.price;
return 0;
getch();
}
答案 2 :(得分:0)
What complier do you use?
After removing #include <conio.h>
and replacing float
with double
, Clang and VC++ both accept this code while GCC complains. I think it is a bug for GCC.
Although this is not an initialization, it is equivalent to call the assignment operator with the initializer-list as an argument. The parameter of the assignment operator is const book&
, and use this initializer-list to initialize this reference is well-defined. The program is also well-defined.
答案 3 :(得分:-1)
您正尝试按ol
初始化b2
。您可以阅读reference以了解如何初始化它
有很多方法。一个简单的方法是:
list initialization