[英]Creating static variables in classes (C++)
So I'm a noob with programming, and I am unsure why I am unable to make a static variable in my class? 所以我是编程新手,我不确定为什么无法在我的课堂上做一个静态变量吗? I got a question from class and I'm not sure if I'm going about it the right way.
我上课时遇到了一个问题,我不确定是否要正确解决问题。 The question is: Create a class with a static member item so that whenever a new object is created, the total number of objects of the class can be reported.
问题是:用静态成员项创建一个类,以便每当创建一个新对象时,都可以报告该类的对象总数。
This is my code so far: 到目前为止,这是我的代码:
#include <iostream>
class ObjectCount
{
public:
ObjectCount();
void reportObjectNo();
private:
static int objectNo = 0;
};
ObjectCount::ObjectCount()
{
objectNo++;
}
void ObjectCount::reportObjectNo()
{
std::cout << "Number of object created for class ObjectCount: " << objectNo << std::endl;
}
int main()
{
ObjectCount firstObject;
firstObject.reportObjectNo();
ObjectCount secondObject;
secondObject.reportObjectNo();
ObjectCount thirdObject;
thirdObject.reportObjectNo();
return 0;
}
And the error I get back is: 我得到的错误是:
ISO C++ forbids in-class initialization of non-const static member 'objectNo'
line 9
I sincerely apologize if this has already been asked, but I couldn't find anything that helped me, if there is a link would be appreciated :) 如果您已经提出了要求,我深表歉意,但是如果有任何链接,我们将不胜感激:)
The error message is telling you that you cannot initialize a non- const
static
member from inside a class. 该错误消息告诉你,你不能初始化非
const
static
从类的内部成员。 This would mean that you would need to change the code to look something more like: 这意味着您将需要更改代码,使其看起来更像:
class ObjectCount
{
public:
ObjectCount();
void reportObjectNo();
private:
static int objectNo;
};
int ObjectCount::objectNo = 0;
C++ lets you declare and define in your class body only static const integral types. C ++允许您在类主体中声明和定义仅静态const整数类型。
class Foo
{
static const int xyz = 1;
};
non-const static member variables must be declared in the class and then defined outside of it.you define it in implementation file ie .cpp 非常量静态成员变量必须在类中声明,然后在类外部定义。您可以在实现文件即.cpp中定义它
int ObjectCount::objectNo = 0;
Also, the proper way to use it would be 另外,正确的使用方式是
ObjectCount::objectNo++;
since, objectNo is associated with class and not with any object. 因为,objectNo与类关联,而不与任何对象关联。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.