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

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

问题描述

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

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 主窗口文件中看到使用第一种方法:

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?

推荐答案

类定义必须在你声明类的同一个命名空间中.

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 成语.在命名空间中声明的 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天全站免登陆