Struct:初始化程序的错误

时间:2015-11-22 23:59:33

标签: c++ visual-c++

对于下面的代码,我收到以下消息。这些是:

1>c:\users\s1\desktop\c++folder\pr5\pr5\pr5.cpp(11): error C2078: too many initializers
1>c:\users\s1\desktop\c++folder\pr5\pr5\pr5.cpp(13): error C2143: syntax error : missing ';' before '.'
1>c:\users\s1\desktop\c++folder\pr5\pr5\pr5.cpp(13): error C2373: 'newBean' : redefinition; different type modifiers
1>c:\users\s1\desktop\c++folder\pr5\pr5\pr5.cpp(12) : see declaration of 'newBean'
1>c:\users\s1\desktop\c++folder\pr5\pr5\pr5.cpp(14): error C2143: syntax error : missing ';' before '.'

这是下面的代码。我该如何修改代码?我已经使struct成员成为静态const。

#include <iostream>
#include <string>
using namespace std;

 struct coffeeBean
{
    static const string name;
    static const string country;
    static const int strength;
};
 coffeeBean myBean = {"yes", "hello", 10 };
 coffeeBean newBean;
 const string newBean.name = "Flora";
 const string newBean.country = "Mexico";
 const int newBean.strength = 9; 

int main( int argc, char ** argv ) {

 cout << "Coffee bean " + newBean.name + " is from " + newBean.country << endl;
 system("pause");
 return 0;
}

2 个答案:

答案 0 :(得分:3)

#include <iostream>
#include <string>
using namespace std;

struct coffeeBean
{
    string name;                     
    string country;                         
    int strength;
};
 coffeeBean myBean = {"yes", "hello", 10 };
 coffeeBean newBean;

int main( int argc, char ** argv ) {

newBean.name = "Flora";
newBean.country = "Mexico";
newBean.strength = 9; 
 cout << "Coffee bean " + newBean.name + " is from " + newBean.country << endl;
 system("pause");
 return 0;
}

一些事情:

如果要初始化变量,请不要在全局范围内执行此操作。

如果要分配给变量,请不要在其上声明类型:

const string newBean.name = "Flora";//declare new variable, or assign to newBean.name ??

只需像这样分配:

newBean.name = "Flora";

如果要拥有变量,请使用static,这对于所有类实例都是通用的。如果你想要一个变量,不同的实例(OOP的常用),不要声明const。

最后,声明常数,如果你计划改变价值。

答案 1 :(得分:-1)

#include <iostream>
#include <string>
using namespace std;

struct coffeeBean
{
    string name; // can't be static because you want more 
                 // than one coffeeBean to have different values
    string country; // can't be const either because newBean 
                    // will default-construct and then assign to the members
    int strength;
};
 coffeeBean myBean = {"yes", "hello", 10 };
 coffeeBean newBean;
 newBean.name = "Flora";
 newBean.country = "Mexico";
 newBean.strength = 9; 

int main( int argc, char ** argv ) {

 cout << "Coffee bean " + newBean.name + " is from " + newBean.country << endl;
 system("pause");
 return 0;
}

固定。看评论。