成员函数参数类型是嵌套类
class Solution {
public:
void func(test t)
{
}
class test
{
};
};
编译这给出了错误
error: unknown type name 'test'
void func(test t)
我在类型测试中添加了一个范围
class Solution {
public:
void func(Solution::test t)
{
}
class test
{
};
};
但这给
test.cpp:47:25: error: no type named 'test' in 'Solution'
void func(Solution::test t)
我认为这是因为该函数test不知道,class test因为它是在它下面声明的。所以我在上面添加了一个声明test
class Solution {
public:
class test;
void func(Solution::test t)
{
}
class test
{
};
};
现在这段代码可以编译(如果我删除了Solution::作用域,它也会编译),但是我有两个问题。
(1) 如果func调用在它下面定义的某个其他成员函数,它可以工作,但是为什么test在这种情况下它会抱怨不知道该类?
(2)Solution::在这种情况下添加 有什么意义吗?
回答
您在这里处理的内容称为类的完整类上下文,它是
类(模板)的完整类上下文是
- 函数体([dcl.fct.def.general]),
- 默认参数([dcl.fct.default]),
- 默认模板参数([temp.param]),
- noexcept-specifier ([except.spec]),或
- 默认成员初始值设定项
在类或类模板的成员规范中。
成员函数的参数不是这个的一部分,所以它们必须是已经定义的类型,在这种情况下不是。一旦您class test;首先添加它,它就会起作用,因为现在类型已声明,这就是函数声明所需的全部内容。
因此,解决方案是先定义test,或者像在上一个示例中一样向前声明它。