结构:初始化程序出错
Struct: errors with initializers
对于下面的代码,我得到了以下消息。这些是:
1>c:userss1desktopc++folderpr5pr5pr5.cpp(11): error C2078: too many initializers
1>c:userss1desktopc++folderpr5pr5pr5.cpp(13): error C2143: syntax error : missing ';' before '.'
1>c:userss1desktopc++folderpr5pr5pr5.cpp(13): error C2373: 'newBean' : redefinition; different type modifiers
1>c:userss1desktopc++folderpr5pr5pr5.cpp(12) : see declaration of 'newBean'
1>c:userss1desktopc++folderpr5pr5pr5.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;
}
#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。
最后,如果您在更改值时执行而不是计划,请声明常量。
#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;
}
已修复。请参阅评论。
相关文章:
- 在C/C++中执行"_dl_init"(程序初始化)是单线程的吗
- 为什么我在初始化带大括号的结构时出错?
- 内存清理程序报告全局对象构造中未初始化值的使用
- 为什么我的 c++ 程序检查不是初始化的变量?
- 使用根/C++时出错:没有匹配的构造函数来初始化'TTree'
- wxWidgets 拖放文件事件处理程序初始化问题(无效static_cast)
- 程序如何知道静态变量是否需要初始化?
- 尝试初始化结构内的联合时出错
- 初始化和终止Qt应用程序的正确方法?
- 指定的初始化程序
- 错误:为函数__THROW__asm提供了初始化程序
- C++引物动态数组初始化程序的数目超过大小
- 在C++初始化程序列表中使用Integer Literals
- 将初始化的矢量作为引用传递时出错
- 程序在初始化期间未与数组一起运行
- 一次崩溃了SDL_MIXER;现在,所有使用SDL_MIXER的程序在初始化时崩溃
- Qt - 如何从应用程序内部初始化某些操作
- 如何在Qt GUI应用程序中初始化具有空值的数组
- 结构:初始化程序出错
- 在一个程序中初始化多个环