Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ forward declaration of a static class member

I have a class:

class M {
public:
    static std::string t[];
};

with an initialization that comes later. I want to use the M::t later in a different class (header file):

class Use {
public:
    void f() { std::cout << M::t[0] << std::endl; }
};

Is there any way to achieve this without including the whole class M for the header file of the Use? I understand that forward declarations do not allow accessing class members, however this beauty is a static one, so it shouldn't be a huge problem for the compiler..

like image 404
arthur Avatar asked Apr 04 '13 08:04

arthur


People also ask

What is forward declaration of a class?

Forward Declaration refers to the beforehand declaration of the syntax or signature of an identifier, variable, function, class, etc. prior to its usage (done later in the program). Example: // Forward Declaration of the sum() void sum(int, int); // Usage of the sum void sum(int a, int b) { // Body }

How do we declare member of a class static?

We can define class members static using static keyword. When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member. A static member is shared by all objects of the class.

How do you forward a declaration?

To write a forward declaration for a function, we use a function declaration statement (also called a function prototype). The function declaration consists of the function header (the function's return type, name, and parameter types), terminated with a semicolon. The function body is not included in the declaration.

What is forward declaration in Objective C?

In Objective-C, classes and protocols can be forward-declared like this: @class MyClass; @protocol MyProtocol; In Objective-C, classes and protocols can be forward-declared if you only need to use them as part of an object pointer type, e.g. MyClass * or id<MyProtocol>.


2 Answers

No, you can't. You can either include the header in the header, or separate the implementation Use::f in an implementation file and include M's header there.

like image 124
Luchian Grigore Avatar answered Oct 05 '22 23:10

Luchian Grigore


There are no partial classes like in C#, where you can define a class in several files.
Since you are making it a public static member, why don't you create a namespace and embed it there?

namespace myns{

std::string t[];

}

You can access it from anywhere then, just like you would have done with a public static class member.

like image 41
bash.d Avatar answered Oct 06 '22 01:10

bash.d