Domanda

Holla , In auto-generated Qt 5 project files by QtCreator There is a declaration of a namespace called Ui in two separate headers and both of them are included in one cpp file

//mainwindow.h
namespace Ui {
class MainWindow;
}



//ui_mainwindow.h
namespace Ui {
class MainWindow: public Ui_MainWindow {};
int x;
}


//mainwindow.cpp
#include "ui_mainwindow.h"
#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

} 

I wonder what happens to the namespace ? is it merged and why this is not considered as redefinition of Class MainWindow ? Thanks in advance.

Thanks for your answers & I found this article about headers including

È stato utile?

Soluzione

  1. It is merged.

  2. The first class MainWindow; is a forward declaration and it's very much intentional; it's used to tell the compiler "there is a class named like that, later I'll define it".

    It is useful since a forward declaration allows you to declare pointers and references without having the full class definition yet, thus allowing you to break dependency circles between classes and keeping down the headers to be included if they aren't really necessary. The forward declaration is later (optionally) replaced by the usual full class definition.

Altri suggerimenti

You can open namespaces as often as you want. The declarations are simply merged. That works the same way as it works for the global namespace already: you can have multiple headers declaring names in the global namespace, too. The declarations seen is just the union of all declarations.

With respect to Ui::MainWindow, the mainwindow.h file doesn't provide a definition. It only provides a declaration. You can declare a class as often as you want in a translation unit. The ui_mainwindow.h file provides a definition of Ui::MainWindow. Within one translation unit you are allowed only one definition of a class.

is it merged

That is correct, and it is not related to Qt.

It is the generic C++ namespace behavior. Namespaces can be occurring in more than one file to have better modularity.

Many libraries use one big namespace for their functionality even though the functionality is distributed among many source and header files.

I would suggest to read the following page for further details about namespace. They surely have a lot longer and more detailed explanation about it:

Namespaces

why this is not considered as redefinition of Class MainWindow ?

class MainWindow;

That is just a forward declaration and you can have any number of them. This is valid as long as you only have one definition. The purpose of this is to speed up the compilation where you do not need to be aware of the exact class representation.

Here you can learn a bit more about forward declaration:

Forward declarations

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top