6

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..

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

nice. You actually answered my other question of recursive inclusions :-)
3

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.

Comments

0

Forward declarations only allow you to use forward-declared-class pointers or references, not members! If you want to use class members like in your example you have to include the class header, even if it's static.

Here is the solution if you don't want to include M.h in your Use.h header:

Use.h

class Use { public: void f(); }; 

Use.cpp

#include "M.h" #include "Use.h" void Use::f() { std::cout << M::t[0] << std::endl; } 

Also, you have to know it's a bad habit to write code in header files, except of course for inline and templates.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.