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_
我将此标头添加到 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.
这篇关于在命名空间中定义类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在命名空间中定义类的方法
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
