簡體   English   中英

結構:初始化器錯誤

[英]Struct: errors with initializers

對於下面的代碼,我收到以下消息。 這些是:

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

固定。 看評論。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM