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 }在这段代码中,我不知道为什么编译器不允许我将值0赋给变量x。 我突出显示导致问题的那一行。
我还注意到,如果我在函数体之前写入int :: sum = 0,程序就可以了。 我只是不明白为什么。 我感谢任何帮助!
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 }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.
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 initialiseQuoting 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).
更多推荐
发布评论