在命名空间中定义类的方式 [英] way of defining class in a namespace

查看:607
本文介绍了在命名空间中定义类的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在标题中的命名空间中定义了一个类,如下所示:

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_

我将此标题添加到main.cpp中,在main()中的一个对象,但它的返回错误 undefined class'classspace :: Aclass'
它的主要

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;
}

当我将类定义为

class classspace::Aclass
{
    //body
};

错误已解决。
我使用第一种方法在Qt mainwindow文件中看到了:

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?

推荐答案

类定义必须在同一个命名空间中, class in。

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

对于Qt示例,在命名空间之外声明的MainWindow不是同一个类

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

它使用 Pimpl idiom 。在命名空间中声明的MainWindow类用作在外部声明的MainWindow类中的成员,并且使用其命名空间限定:

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;

这个类的定义放在别的地方(在不同的.cpp文件中)在 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.

这篇关于在命名空间中定义类的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆