"Y does not name a type"错误C++
"Y does not name a type" error in C++
我不知道该怎么搜索才能找到这个问题的解释,所以我问。
我有这段代码报告错误:
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;
但是如果我把值赋值放在main中,它可以工作:
struct Settings{
int width;
int height;
} settings;
main () {
settings.width = 800; // no error
settings.height = 600; // no error
你能告诉我为什么吗?
编辑:
关于Ralph Tandetzky的回答,这里是我的完整结构代码。你能告诉我如何赋值,就像你对我的代码片段结构体做的那样吗?
struct Settings{
struct Dimensions{
int width;
int height;
} screen;
struct Build_menu:Dimensions{
int border_width;
} build_menu;
} settings;
在c++中不能将赋值置于函数的上下文之外。如果您对有时在函数的上下文中看到=
符号被使用感到困惑,例如:
int x = 42; // <== THIS IS NOT AN ASSIGNMENT!
int main()
{
// ...
}
这是因为=
符号也可以用于初始化。在您的示例中,您没有初始化数据成员width
和height
,您正在为它们分配一个值。
在c++ 11中可以写
struct Settings {
int width;
int height;
} settings = { 800, 600 };
来修复你的错误。出现错误是因为您试图在函数体外部赋值。可以在函数外部初始化全局数据,但不能赋值全局数据。
编辑:关于你的编辑,只需写
Settings settings = {{800, 600}, {10, 20, 3}};
由于继承的关系,我不能100%确定这是否有效。我建议在这种情况下避免继承,并将Dimensions
作为成员数据写入Build_menu
结构中。继承迟早会给你带来各种麻烦,当你这样使用的时候。比起继承,更喜欢组合。当你这样做的时候,它看起来会像
Settings settings = {{800, 600}, {{10, 20}, 3}};
相关文章:
- std::unordered_map 类型对象声明期间出现"field has incomplete type"错误
- 将系数存储在头文件的数组中("does not name a type"错误)
- 尝试打开 ifstream 时出现"Incomplete type"错误
- 在 C++ 中使用命名空间时出现"does not name a type"错误
- 已声明时"Does not name a type"错误
- unordered_set .find 方法无法编译的 C++ "expression must have class type"错误
- 模板类和'invalid use of incomplete type'错误
- 在接口文件中使用模板时出现"not a type"错误的函数指针
- 我需要在不使用前向声明的情况下相互包含两个头文件,导致"incomplete type"错误
- 在 c++ 中,如果包含标头,为什么我会收到'does not a name of type'错误?
- 什么原因导致我的"‘FatalError’ in namespace ‘Foam’ does not name a type"错误?
- 为什么我会收到"Expression must have a class type"错误?(C++)
- 无法使用其他文件中的枚举:" does not name a type"错误
- 如何修复"static assertion failed: template argument not an integral type"错误?
- "Expression must have class type"错误
- "unresolved overloaded function type"错误并将运算符作为函数参数传递
- C++模板"class type"错误
- "Allocating an object of abstract class type"错误,尽管所有函数都有实现
- "does not have a class type"错误
- "expected unqualified-id before 'void'" & "string in class does not name a type" 错误