c++相同类型的类成员

发布于 2024-12-03 16:44:35 字数 171 浏览 1 评论 0原文

我遇到以下情况:

class Foo
{
public:
  static const Foo memberOfFoo;

  ........
}

所以问题是我无法在声明它的同一行中初始化它,并且我无法通过构造函数中的初始化列表初始化它,有人知道该怎么做吗?

I have the following situation:

class Foo
{
public:
  static const Foo memberOfFoo;

  ........
}

So the thing is I can't initialize it in the same line where I declared it, and, I can't initialize it via Initializations List in the constructor, does anyone know what to do?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一念一轮回 2024-12-10 16:44:35

然后将其放在类定义之外:

const Foo Foo::memberOfFoo = whateverValue;

这就是 Foo::memberOfFoo 的定义,它可以提供初始化程序并且必须进入 .cpp 文件(与任何其他文件一样)其他对象的定义,它在整个程序中只能出现一次,否则会出现链接器错误)。

有时您会发现代码没有静态数据成员的定义:

struct A {
  // sometimes, code won't have an "const int A::x;" anywhere!
  static const int x = 42;
};

仅当 A::x 从未被取地址且从未传递给引用参数时,省略这样的定义才有效。更正式的说法是:“当 A::x 的所有使用都立即读取 A::x 的存储值时”。许多静态整数常量都是这种情况。

Put this outside of the class definition then:

const Foo Foo::memberOfFoo = whateverValue;

That is the definition of Foo::memberOfFoo, which can supply an initializer and has to go into the .cpp file (like any other definition of objects, it can only appear once in the whole program, otherwise you will get linker errors).

Sometimes you will find code that doesn't have definitions for its static data members:

struct A {
  // sometimes, code won't have an "const int A::x;" anywhere!
  static const int x = 42;
};

Omitting the definition like that is valid only if A::x is never address-taken and never passed to reference parameters. A more formal way to say when it is valid to omit the definition is: "When all uses of A::x immediately read the stored value of A::x". That's the case for many static integer constants.

梦旅人picnic 2024-12-10 16:44:35

除常量整型类型之外的类静态需要/可以在定义时初始化。您需要通过添加在某处声明您的(不是这样)memberOfFoo

const Foo Foo::memberOfFoo = /*construct here*/;

Class statics other than constant integral types need to/can be initialized at the point of definition. You need to declare your (not so)memberOfFoo somewhere, by adding

const Foo Foo::memberOfFoo = /*construct here*/;
灰色世界里的红玫瑰 2024-12-10 16:44:35

这就是你如何实现初始化......

class Foo
{
public:
    static const Foo memberOfFoo;

    Foo(int, double)
    {
        ...
    };
};

const Foo Foo::memberOfFoo(42, 3.141592654);

...

This is how you can implement initialization...

class Foo
{
public:
    static const Foo memberOfFoo;

    Foo(int, double)
    {
        ...
    };
};

const Foo Foo::memberOfFoo(42, 3.141592654);

...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文