-1

嗨,我是 C++ 新手,在 dev-c++ 中测试 C++ 代码中的结构。但它没有编译并给出错误。它与 dev-c++ 中预处理器指令中的 .h 扩展配合得很好。所以我不这么认为它带有.h扩展问题

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
struct car
{
  const int MAX=10;
  char model[MAX];
  char spare_part[MAX];
  float cost;        

          }
int main()
{

    car BMW ;
    BMW.model[MAX]="SLR-8 S";
    BMW.spare_part[MAX]="SILENCER";
    BMW.cost=175.56F;


    cout << setw(50) << "\n\n WELCOME TO SHOWROOM" << endl << endl;
    cout <<  "CAR MODEL: " << BMW.model[MAX] << endl;
    cout << "SPARE PART: " << BMW.spare_part[MAX] << endl;
    cout << "COST OF PRODUCT: " << BMW.cost[MAX] << endl;  
    return 0;
    }

编译器日志是:

Compiler: Default compiler
Executing  g++.exe...
g++.exe "D:\cdev\projects\structure.cpp" -o "D:\cdev\projects\structure.exe"    -I"D:\cdev\Dev-Cpp\lib\gcc\mingw32\3.4.2\include"  -I"D:\cdev\Dev-Cpp\include\c++\3.4.2\backward"  -I"D:\cdev\Dev-Cpp\include\c++\3.4.2\mingw32"  -I"D:\cdev\Dev-Cpp\include\c++\3.4.2"  -I"D:\cdev\Dev-Cpp\include"   -L"D:\cdev\Dev-Cpp\lib" 
In file included from D:/cdev/Dev-Cpp/include/c++/3.4.2/backward/iostream.h:31,
             from D:\cdev\projects\structure.cpp:1:

D:/cdev/Dev-Cpp/include/c++/3.4.2/backward/backward_warning.h:32:2: warning: #warning This file includes at least one deprecated or antiquated header. Please consider using one of the 32 headers found in section 17.4.1.2 of the C++ standard. Examples include substituting the <X> header for the <X.h> header for C++ includes, or <iostream> instead of the deprecated header <iostream.h>. To disable this warning use -Wno-deprecated.

D:\cdev\projects\structure.cpp:6: error: ISO C++ forbids initialization of member `MAX'

D:\cdev\projects\structure.cpp:6: error: making `MAX' static

D:\cdev\projects\structure.cpp:13: error: new types may not be defined in a return type

D:\cdev\projects\structure.cpp:13: error: extraneous `int' ignored

D:\cdev\projects\structure.cpp:13: error: `main' must return `int'

D:\cdev\projects\structure.cpp: In function `int main(...)':

D:\cdev\projects\structure.cpp:16: error: `MAX' undeclared (first use this function)

D:\cdev\projects\structure.cpp:16: error: (Each undeclared identifier is reported only 
once for each function it appears in.)

Execution terminated
4

2 回答 2

2

stuct 中的值应该在构造函数中初始化,或者应该是静态的。喜欢:

struct car
{
  static const int MAX=10;
  ...

结构定义后缺少分号。它应该是这样的:

struct car
{
  static const int MAX=10;
  char model[MAX];
  char spare_part[MAX];
  float cost;        

};
于 2013-10-15T06:37:46.447 回答
1

检查你的分号。在结构的关闭 } 之后需要一个。

另外,声明 MAX 变量static,即

{
    static const int MAX=10;

但是编译器很好地告诉你...

第三个错误来自您MAX在内部声明的事实,car您必须相应地将其引用为car::MAX. 但实际上,整个BMW.model[MAX]="SLR-8 S";声明并没有真正的意义。这意味着'将字符串“SLR-8 S”分配给BMW.model中最后一个字符之后的字符'(对于char [MAX],有效索引从0开始,然后转到(MAX-1)!) . 最好使用std::string而不是char model[MAX],这更容易处理!例如:

struct car
{
    std::string model;

然后你可以简单地说

BMW.model="SLR-8 S";
于 2013-10-15T06:37:46.083 回答