将值赋给静态变量时出错(Error assigning value to a static variable)

编程入门 行业动态 更新时间:2024-10-15 18:29:00
将值赋给静态变量时出错(Error assigning value to a static variable)

在这段代码中,我不知道为什么编译器不允许我将值0赋给变量x。 我突出显示导致问题的那一行。

class List{ private: int p; public: static int x; void total(); }; void List::total(List *a){ x + = a -> p; cout<<x; getch(); x=0; // problem here }

我还注意到,如果我在函数体之前写入int :: sum = 0,程序就可以了。 我只是不明白为什么。 我感谢任何帮助!

In this piece of code I don't know why the compiler doesn't let me assign the value 0 to variable x. I highlighted the line that cause the problem.

class List{ private: int p; public: static int x; void total(); }; void List::total(List *a){ x + = a -> p; cout<<x; getch(); x=0; // problem here }

I also noticed that if I write int List::sum=0 before the function body, program works just fine. I just don't understand why. I appreciate any help!

最满意答案

您已在类中声明了静态但尚未为其定义变量。

class List{ private: int p; public: static int x; // this is just a declaration void total(); };

您需要定义它,通常在关联的cpp文件中:

List::x = 0; // define variable and initialise

引自这里 :

9.4.2静态数据成员 静态数据成员在其类定义中的声明不是定义,除了cv-qualified void之外可能是不完整的类型。 静态数据成员的定义应出现在包含成员类定义的命名空间范围内。 在命名空间范围的定义中,静态数据成员的名称应使用::运算符通过其类名限定。 静态数据成员定义中的初始化表达式在其类( basic.scope.class )的范围内。

You have declared the static in your class but have not defined a variable for it.

class List{ private: int p; public: static int x; // this is just a declaration void total(); };

You need to define it, normally in the associated cpp file:

List::x = 0; // define variable and initialise

Quoting from here:

9.4.2 Static data members The declaration of a static data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void. The definition for a static data member shall appear in a namespace scope enclosing the member's class definition. In the defi- nition at namespace scope, the name of the static data member shall be qualified by its class name using the :: operator. The initializer expression in the definition of a static data member is in the scope of its class (basic.scope.class).

更多推荐

本文发布于:2023-08-01 22:49:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1365781.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   静态   将值赋   Error   variable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!