开发者

Putting classes inside namespaces

I see that Qt puts a class inside the 开发者_StackOverflow中文版Ui interface like this:

namespace Ui {
    class MainWindow;
}

class MainWindow : public QMainWindow
{
    ...

Is this method the same as enclosing the entire class inside the namespace? It certainly looks cleaner.


No, in your example Ui::MainWindow is a different class than the MainWindow class defined in the global namespace.

Behold:

namespace Ui {
    class MainWindow;
}

class MainWindow
{

};

int main()
{
    Ui::MainWindow mw; // fails due to incomplete type
}

This code won't compile, since Ui::MainWindow is an incomplete type.

Most likely, the Qt code was just using a forward declaration. You can forward declare the class in a namespace, but you still must actually implement the class in the same namespace, or else it is not the same class.


The two classes are different. What you are talking about is not Qt proper, but the results of using the Designer to create UI objects. Qt rightly does this because they are attempting to keep the generated code separated from anything you might add as logic, such as signal handing functions, etc... Otherwise they would have to be able to do one of three things:

1) Try to tell the difference between what the designer needs to modify and what the user would not want it to...solving conflicts in some mysterious way they'd have to come up with arbitrarily.

2) Simply override anything the user's changed.

3) Not change the file if the user hasn't deleted it or something.

The first is a whole lot of work and no matter what the developers chose, someone, somewhere would be inconvenienced. The second alternative of course would upset people because all the slot code they write would be destroyed with each change to the UI, which would be VERY inconvenient almost all of the time. The third of course would not be convenient for a number of reasons.

So what they do is separate the part of the UI object generated by the Designer and the part written by the developer/user. This allows them to simply destroy changes to certain well defined areas, while letting the developer add the behavior they need to without having to keep adding it.

It's not something you'd normally do in regular program design. It's done this way to solve a fairly specific problem having to do with automatically generated code. It's a fairly well thought out approach IMNSHO.


Generally, uic makes headers that look like this:

      class Ui_MainWindow
      {
         // auto-generated stuff
      };

      namespace Ui {
            class MainWindow: public Ui_MainWindow {};
      }

This lets you use MainWindow as the name of your class, and still call the auto-generated UI class MainWindow. Note that Ui::MainWindow is a full class definition, not a forward declaration.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜