首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Struct:初始化器错误

Struct:初始化器错误
EN

Stack Overflow用户
提问于 2015-11-23 07:59:33
回答 2查看 75关注 0票数 0

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

代码语言:javascript
复制
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 '.'

这是下面的代码。我怎么才能修复代码呢?我已将结构成员设置为静态常量。

代码语言:javascript
复制
#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;
}
EN

回答 2

Stack Overflow用户

发布于 2015-11-23 08:30:03

代码语言:javascript
复制
#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;
}

有几件事:

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

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

代码语言:javascript
复制
const string newBean.name = "Flora";//declare new variable, or assign to newBean.name ??

就像这样分配给它:

代码语言:javascript
复制
newBean.name = "Flora";

如果你想拥有一个类的所有实例都通用的变量,那么可以使用static。如果你想要一个变量,它在不同的实例中是不同的(通常使用OOP),不要声明const。

最后,声明常量,如果你不打算改变的值。

票数 3
EN

Stack Overflow用户

发布于 2015-11-23 08:19:54

代码语言:javascript
复制
#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;
}

已修复。请参见注释。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33861800

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档