对于下面的代码,我得到了以下消息。它们是:
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 '.'这是下面的代码。我怎么才能修复代码呢?我已将结构成员设置为静态常量。
#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;
}发布于 2015-11-23 08:30:03
#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。
最后,声明常量,如果你不打算改变的值。
发布于 2015-11-23 08:19:54
#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;
}已修复。请参见注释。
https://stackoverflow.com/questions/33861800
复制相似问题