问题
I don't know what to search to find an explanation for this, so I am asking.
I have this code which reports error:
struct Settings{
int width;
int height;
} settings;
settings.width = 800; // 'settings' does not name a type error
settings.height = 600; // 'settings' does not name a type error
int main(){
cout << settings.width << " " << settings.height << endl;
but if I put the value assignment in main, it works:
struct Settings{
int width;
int height;
} settings;
main () {
settings.width = 800; // no error
settings.height = 600; // no error
Can you explain me why?
EDIT:
Regarding to Ralph Tandetzky's answer, here is my full struct code. Could you show me how to assign the values as you did with my snippet struct?
struct Settings{
struct Dimensions{
int width;
int height;
} screen;
struct Build_menu:Dimensions{
int border_width;
} build_menu;
} settings;
回答1:
You cannot put assignments outside the context of a function in C++. If you're puzzled by the fact that you sometimes saw the =
symbol being used outside the context of a function, such as:
int x = 42; // <== THIS IS NOT AN ASSIGNMENT!
int main()
{
// ...
}
That's because the =
symbol can be used for initialization as well. In your example, you are not initializing the data members width
and height
, you are assigning a value to them.
回答2:
In C++11 you can write
struct Settings {
int width;
int height;
} settings = { 800, 600 };
in order to fix your bug. The error appears because you're trying to assign a value outside a function body. You can initialize but not assign global data outside of a function.
EDIT:
Concerning your edit, just write
Settings settings = {{800, 600}, {10, 20, 3}};
I'm not 100% sure, if this works though, because of the inheritance. I would recommend to avoid inheritance in this case and write the Dimensions
as member data into your Build_menu
structure. Inheritance will sooner or later give you all kinds of trouble, when used this way. Prefer composition to inheritance. When you do that, it's gonna look like
Settings settings = {{800, 600}, {{10, 20}, 3}};
来源:https://stackoverflow.com/questions/16938810/y-does-not-name-a-type-error-in-c