结构:初始化程序出错

Struct: errors with initializers

本文关键字:程序出错 初始化 结构      更新时间:2023-10-16

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

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;
}

已修复。请参阅评论。