2017-12-18 172 views
0
#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: no match for 'operator=' (operand types are 'book' and '')|

C:\Users\shandude\Documents\codeblock\cprog\struct2.cpp|5|note: no known conversion for argument 1 from '' to 'const book&'|

+0

你觉得'b2 = {100,“C++ by saurabh”,105.2}; '应该这样做? – Galen

+0

关闭主题,但最后两行'return 0;'和'getch();'应该颠倒过来。 'getch();'什么都不做。应用程序将在此行被调用之前返回。另外:在全局范围内使用名称空间标准不是一个好主意,也不是好的做法。 –

+0

应该编写_initialize_'b2'(创建'b2'的一部分)还是给'b2(创建后的值)赋一个值? – chux

回答

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(); 
} 
1

您可以使用:

b2 = book{100,"c++ by saurabh",105.2}; 

PS

我将建议改变成员变量titlestd::string。使用char阵列来表示用户代码串是在2017年

struct book 
{ 
    int bookid; 
    std::string title; 
    float price; 
}; 
+0

1998年已经不是时代错误了吗? ;) – Quentin

-1

您正试图通过list initialization初始化b2不合时宜。您可以阅读reference以了解如何对其进行初始化。
有很多方法。一个简单的方法是:

book b2{100,"c++ by saurabh",105.2}; 
+2

'b2'已经存在。代码试图*分配给它,这是不同的初始化 –

+0

你的解决方案给了我确切的答案我究竟在哪里我困惑,非常感谢你。 – shandude

0

你使用什么编译器?

删除#include <conio.h>并将float替换为double后,Clang和VC++都接受此代码,而GCC抱怨。我认为这是GCC的一个bug。

虽然这不是初始化,但它等同于将初始化程序列表作为参数调用赋值运算符。赋值运算符的参数是const book&,并使用此初始化程序列表来初始化此引用已定义良好。该计划也是明确的。

相关问题