* kk565:
> Apologies if this has been asked already, but my searches have turned up
> nothing.
>
> I have a class declaration inside a header file similar to this:
>
> struct MyClass
> {
> class mytype_a *m1;
> class mynamespace1::mynamespace2::mytype_b *m2;
> };
>
> Whereas just mytype_a compiles just fine, at the second member
> declaration the compiler (GCC 4) gives the error:
> ‘mynamespace1’ has not been declared
>
> My assumption was that since this is a just a pointer declaration, the
> compiler would not need to know the actual details of the type (at least
> at this stage)
>
> To fix this, does it mean that I have to include the header file
> containing the mytype_b type (and all namespace declarations)? or is
> there a way of just letting the compiler know about these namespaces
> without including the actual declarations?
The following compiles fine with three compilers:
class mytype_a;
namespace mynamespace1
{
namespace mynamespace2
{
class mytype_b;
}
}
struct MyClass
{
class mytype_a *m1;
class mynamespace1::mynamespace2::mytype_b *m2;
};
int main() {}
However, the "class" keyword is superfluous, write just
struct MyClass
{
mytype_a *m1;
mynamespace1::mynamespace2::mytype_b *m2;
};
By the way, since that indicates that you're new to C++: it's generally
not a good idea to use raw pointers directly. Depending on what you're
using them for consider library classes such as std::vector or smart
pointers such as boost::shared_ptr. That takes care of a lot of
problems, including the ambiguity about what the pointers are used for.
> Also my first instinct was to use something like this
> struct MyClass
> {
> using namespace mynamespace1;
> };
>
> however this appears not be valid C++. Is there anyway of declaring used
> namespaces or components from namespaces within a class
> declaration/implementation?
No, but you can (for example) define a namespace alias outside of the class:
namespace blah = mynamespace1::mynamespace2;
struct MyClass
{
mytype_a *m1;
blah::mytype_b *m2;
};
Cheers, & hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
|