Defining unnamed member functions of a class?

I currently have two unnamed classes defined in my Foo.h:

class Foo {
public:
    Foo();

    class {
    private:
        int x;
        int y;
    public:
        int GetX() { return x; }
        int GetY() { return y; }
    } Sub1;

    class {
    private:
        int x;
    public:
        int GetX() { return x; }
    } Sub2;
}

      

This code compiles just fine and is used like this:

 Foo temp;
 int Ax, Ay, Bx;
 Ax = temp.Sub1.GetX();
 Ay = temp.Sub1.GetY();
 Bx = temp.Sub2.GetX();

      

However, now I want to move the definitions of the member function to the original file. The only way I know to split this class into a header file and a source file is to name the classes:

foo.h:

class Foo {

private:    
    class A {
    private:
        int x;
        int y;
    public:
        int GetX();
        int GetY();
    };

    class B {
    private:
        int x;
    public:
        int GetX();
    };

public:
    Foo();
    A Sub1;
    B Sub2;

}

      

foo.cpp:

int Foo::A::GetX() { return x; }
int Foo::A::GetY() { return y; }
int Foo::B::GetX() { return x; }

      

This code is not what I want, however, as it is ugly and I didn't want the named class to be in the first place.

Is it possible to split a class into a header file and a source file? Or is it just bad code design?

+3


source to share


1 answer


This is unfortunately not possible. §9.3 / 5:

If a member function definition is lexically outside of its class , the member function name::

definition must be assigned the class name using an operator .



Since the class name does not exist, outside class definitions for member functions are not allowed. The fact that GCC allows decltype specifiers in this context is a bug.

+1


source







All Articles