简体   繁体   English

C ++:如何初始化非整数类型的静态成员变量?

[英]C++: How to initialize static member variables which are not integral types?

How can I initialize a static object in c++? 如何在c ++中初始化静态对象? I'm looking for something like static block in java. 我正在寻找像java中的静态块一样的东西。

I tried this: 我试过这个:

Foo.hpp Foo.hpp

class Foo{
    public:
    static Bar b;
    static String s;
    static Bar setB();
};

Foo.cpp Foo.cpp中

Bar Foo::b = Foo::setB();
String Foo::s = "something";
Bar Foo::setB()
{
    Bar bb;
    bb.use(s);
    return bb;
}

There is no compile error, but it's not working. 没有编译错误,但它无法正常工作。

Many thanks 非常感谢

Your code: 你的代码:

class Foo{
    public:
    static Bar b;
    static Bar setB();
}

Your comment: 你的评论:

There is no compile error 没有编译错误

That is not correct . 这是不正确的 It can not compile, due to missing semicolon. 由于缺少分号,它无法编译。

When that is pointed out, most SO posters then claim in some comment that "but it's just a typing mistake, I will correct it", thus compounding the error by invalidating already posted answers. 当指出这一点时,大多数SO海报然后在一些评论中声称“但这只是打字错误,我会纠正它”,从而通过使已经发布的答案无效来加剧错误。

In short, when you post code, do copy and paste the real code . 简而言之,当您发布代码时,请复制并粘贴实际代码 Don't retype it. 不要重新输入。 Copy and paste. 复制和粘贴。

Now, to the core question, the continuation of the above comment, that 现在,关于核心问题,继续上述评论,即

it's not working. 它不起作用。

Well, assuming that your real code has the appropriate semicolons, and that Bar is defined, etc., then also that part is just plain wrong . 好吧,假设您的真实代码具有适当的分号,并且定义了Bar等,那么该部分也是完全错误的

I tested it with Visual C++ and MingW g++, and (when corrected for semicolons etc.) it works just OK. 我使用Visual C ++和MingW g ++测试它,并且(当校正分号等时)它的工作正常。

Bar needs a no-args constructor so that it can initialize itself to the expected value. Bar需要一个no-args构造函数,以便它可以将自己初始化为期望值。

No need for Foo::setBar() since Foo will already have the Bar instance. 不需要Foo::setBar()因为Foo已经有了Bar实例。

Your example works, other than the fact that you didn't actually initialize anything: 您的示例有效,除了您实际上没有初始化任何内容的事实:

#include <iostream>

class Foo{
public:
    static int b;
    static int setB();
};

int Foo::b = Foo::setB();
int Foo::setB()
{
    int bb;
    bb = 42;  // Not in your example
    return bb;
}

int main()
{
    std::cout << 42 << std::endl;
}

This prints 42. (Note that I've changed "Bar" to "int" since you didn't post a definition of Bar.) 这打印42.(注意我已经将“Bar”更改为“int”,因为您没有发布Bar的定义。)

root cause : no semicolon at the end of the class definition. 根本原因:类定义末尾没有分号。 Works perfectly when I put one. 当我放一个时工作得很好。

suggestions: Please give more code(the whole if possible) whenever you ask questions and please don't type the code again instead just copy paste it. 建议:无论何时提出问题,请提供更多代码(如果可能的话,请提供更多代码),请不要再次输入代码,只需复制粘贴即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM