为什么一个类允许有一个自身的静态成员,但不是一个非静态成员? [英] Why is a class allowed to have a static member of itself, but not a non-static member?

查看:171
本文介绍了为什么一个类允许有一个自身的静态成员,但不是一个非静态成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class base {
public:
base a;
};

它会导致编译错误。

  class base {
public:
static base a;
};

而此代码不会导致编译错误

static 类成员不存储在类实例中,这就是为什么 static

将对象存储在同一类型的另一个对象内会破坏运行时 - 无限大小,对吧?



sizeof 会返回什么?对象的大小需要由编译器知道,但由于它包含一个相同类型的对象,这是没有意义的。


class base {
public:
    base a;
};

It gives compilation error.

class base {
public:
    static base a;
};

whereas this code does not give compilation error

解决方案

Because static class members are not stored in the class instance, that's why a static would work.

Storing an object inside another object of the same type would break the runtime - infinite size, right?

What would sizeof return? The size of the object needs to be known by the compiler, but since it contains an object of the same type, it doesn't make sense.

这篇关于为什么一个类允许有一个自身的静态成员,但不是一个非静态成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆