way of defining class in a namespace

前端 未结 6 768
悲哀的现实
悲哀的现实 2020-12-11 08:11

I defined a class in a namespace in a header as follows

#ifndef _c1_
#define _c1_

namespace classspace
{
    class Aclass;
}

class Aclass
{
    //body
};

         


        
6条回答
  •  醉酒成梦
    2020-12-11 08:41

    namespace classspace
    {
        class Aclass;
    }
    

    This declares a class inside a namespace.

    class Aclass
    {
        //body
    };
    

    This declares and defines a different class with the same name in the global namespace

    class classspace::Aclass
    {
        //body
    };
    

    This defines the class you previously declared in the namespace.

    void main()
    {
        classspace::Aclass b;
    }
    

    This tries to instantiate the class declared in the namespace. If that class hasn't been defined (only declared), then it is incomplete and can't be instantiated.

    The Qt example involves two classes: Ui::MainWindow, and MainWindow in the global namespace. The one in Ui has only been declared, so is incomplete in the header. You can do various things with it, such as declare a pointer to it, but you can't instantiate it.

    Presumably, there is a separate source file which defines the Ui class, instantiates one, and sets the pointer to point at it.

    By the way, you shouldn't use reserved names for your include guards, or for anything else. Also, the return type of main must be int.

提交回复
热议问题