头文件中声明的typedef在源文件中不可用

typedef declared in header file not available in source file

本文关键字:源文件 typedef 文件 声明      更新时间:2023-10-16

我在头文件中定义了一个类myclass,在private:部分中定义了typedef

typedef int inttest;

我的源文件包括这个头文件,但当试图像一样使用源文件中的typedef时

inttest myclass::foo() { }

我得到错误:

error: 'inttest' does not name a type

为什么会这样?我是否还需要在源文件中声明typedef

首先,typedef是在类的作用域中定义的。因此,如果将typedef用作返回类型的非限定名称,编译器将找不到它的定义。你可以写例如

myclass::inttest myclass::foo() { }

但是,编译器将再次发出错误,因为typedef被定义为private。

编辑:对不起。我展示的函数的定义将被编译。

然而,在调用函数的代码中,您需要编写

myclass a;
int i = a.foo();

myclass a;
auto i = a.foo();

你可以不写

myclass a;
myclass::inttest i = a.foo();