简体   繁体   中英

C++ defining static object inside class

I have a class A in "ah":

#include "b.h"

class A {
public:
    static B b;
}

I want to initialize b in another function

In "main.cpp":

#include "a.h"
#include "b.h"

int main () {
    ....
    B A::b = B(arg1, arg2);

But the syntax checker give me the error: "member A::b cannot be defined in the current scope." What is the correct way of doing this?

You may set the value in main() but the definition has to be in the global scope:

#include "a.h"
#include "b.h"

B A::b; // <<<<<<

int main () {
    ....
    A::b = B(arg1, arg2);
 // ^^^^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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