Putting classes inside namespaces

I see that Qt places the class inside the Ui interface as follows:

 namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { ... 

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

+4
source share
3 answers

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

Here:

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

This code will not compile since Ui::MainWindow is an incomplete type.

Most likely, the Qt code just used a forward declaration. You can redirect the class declaration to a namespace, but you should still implement the class in the same namespace, otherwise it is not the same class.

+9
source

Two classes are different. What you are talking about does not correspond to Qt, but to the results of using the constructor to create user interface objects. Qt does this correctly because they try to keep the generated code separate from everything that you could add as a logical one, for example, signal transfer functions, etc. Otherwise, they would have to do one of three things:

1) Try to talk about the difference between what the developer has to change and the fact that the user would not want to ... resolve conflicts in some mysterious way that they would have to do arbitrarily.

2) Just redefine everything that the user has changed.

3) Do not modify the file if the user has not deleted it or something like that.

The first is a lot of work and no matter what the developers chose, someone somewhere would be uncomfortable. The second alternative, of course, would upset people, because all recorded slot codes would be destroyed every time the user interface changes, which would be very inconvenient almost all the time. A third, of course, would not be convenient for a number of reasons.

Thus, what they do is a separate part of the user interface object generated by the Designer and a part written by the developer / user. This allows them to simply undo changes in certain well-defined areas, allowing the developer to add the behavior they need without the need to add it.

This is not what you usually do in a regular program design. This was done to solve a rather specific problem related to automatically generated code. This is a pretty well thought out IMNSHO approach.

+1
source

Typically, uic creates headers that look like this:

  class Ui_MainWindow { // auto-generated stuff }; namespace Ui { class MainWindow: public Ui_MainWindow {}; } 

This allows you to use MainWindow as the name of your class and still call the MainWindow autogenerated user interface. Note that Ui::MainWindow is a full class definition, not a forward declaration.

0
source

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


All Articles