Is a forward class declaration interchangeable with a class keyword in a place of use?

Are these two equivalents?

Code 1:

class B;

class A {
public:
    B fun1() const;
    B* m_b;
};

extern void myfun( const B& b );

Code 2:

class A {
public:
    class B fun1() const;
    class B* m_b;
};

extern void myfun( const class B& b );

Or are there some issues with using the programming style presented in code 2?

+4
source share
1 answer

These are different if you have a closing area.

Case 1:

class B { };
namespace test {
    class B;  // declares test::B

    class A {
    public:
        B fun1() const; // refers to test::B
        B* m_b;         // also refers to test::B
    };

    class B { int x; };  // defines test::B
}

Case 2:

class B { };
namespace test {
    class A {
    public:
        class B fun1() const; // refers to ::B
        class B* m_b;         // also refers to ::B
    };

    class B { int x; };  // defines test::B
}

More details:

class B;is one of two things. This is either a renewal or a forward declaration that introduces the name Binto the current scope (ยง9.1 [class.name] / p2 of the standard).

class B . -, , , B, (ยง3.4.4 [basic.lookup.elab]/p2, ยง9.1 [class.name]/p3 note). , .

, . , . , , ; , , , (ยง3.3.2 [basic.scope.pdecl]/p7). , ; , .

? -, , . -, . , , test::B test::A, class B test::A test::B, ::B. -, , ?

+4

Source: https://habr.com/ru/post/1546087/


All Articles