成员变量
类中是否可以有一个不是static
但需要定义的成员变量 (因为定义静态变量是为了保留内存)?如果是这样,我可以举个例子吗?如果不是,那么为什么静态成员是唯一可定义的成员?
BJARNE 说如果你想将成员用作对象,则必须定义它。
但是当我显式定义成员变量时,我的程序显示错误:
class test{
int i;
int j;
//...
};
int test::i; // error: i is not static member.
Can there be a member variable in a class which is not static
but which needs to be defined
(as a static variable is defined for reserving memory)? If so, could I have an example? If not, then why are static members the only definable members?
BJARNE said if you want to use a member as an object ,you must define it.
But my program is showing error when i explicitly define a member variable:
class test{
int i;
int j;
//...
};
int test::i; // error: i is not static member.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在您的示例中,在类中声明
i
和j
也定义了它们。请参阅此示例:
您现在可以通过声明
Foo
类型的对象来访问a
,如下所示:b
略有不同:因为它是static
它对于Foo
的所有实例都是相同的:对于以上所有内容将打印
b
是 10。In your example, declaring
i
andj
in the class also defines them.See this example:
You can now access
a
by declaring an object of typeFoo
, like this:It's a little different for
b
: Because it isstatic
it the same for all instance ofFoo
:For the above all will print that
b
is 10.在这种情况下,您可以使用
test
构造函数的初始化列表来定义实例的初始值,如下所示:in that case, you would use the initialization list of
test
's constructor to define the initial values for an instance like so:该定义为一个整数保留了空间,但是对于您创建的类的每个实例,实际上都会有一个单独的整数。如果您的程序创建了那么多
test
实例,那么可能会有一百万个。每次创建类的实例时,都会在运行时为非静态成员分配空间。它由类的构造函数初始化。例如,如果您希望在每个实例中将整数
test::i
初始化为数字 42,您可以像这样编写构造函数:然后,如果您这样做,
您将得到两个对象,每个都包含一个值为 42 的整数。(当然,该值之后可以更改。)
That definition reserves space for one integer, but there'll really be a separate integer for every instance of the class that you create. There could be a million of them, if your program creates that many instances of
test
.Space for a non-static member is allocated at runtime each time an instance of the class is created. It's initialized by the class's constructor. For example, if you wanted the integer
test::i
to be initialized to the number 42 in each instance, you'd write the constructor like this:Then if you do
you get two objects, each of which contains an integer with the value 42. (The values can change after that, of course.)