Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

c++ - way of defining class in a namespace

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...