Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

#ifndef _c1_
#define _c1_

namespace classspace
{
    class Aclass;
}

class Aclass
{
    //body
};

#endif _c1_

I added this header to main.cpp and made an object in main() but its returning error that undefined class 'classspace::Aclass' its my main

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

when I defined class as

class classspace::Aclass
{
    //body
};

error resolved. I saw in Qt mainwindow file using first approach:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

is working without any error. what is my mistake in the first approach?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
180 views
Welcome To Ask or Share your Answers For Others

1 Answer

The class definition must be in the same namespace you declared the class in.

As for the Qt example, the MainWindow declared outside of the namespace isn't the same class.

It uses the Pimpl idiom. The MainWindow class declared in the namespace is used as a member in the MainWindow class declared outside, and is qualified with its namespace :

Ui::MainWindow* ui;

The definition of this class is put somewhere else (in a different .cpp file) where it should be in the Ui namespace, or with definitions prefixed with the namespace.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...