[英]C++: cannot define member function
Could you please advise why I am getting the error in the code below? 您能告诉我为什么我在下面的代码中得到错误吗?
error: cannot define member function ‘Test<int>::Printer::Print’ within ‘Test<int>’
I am using gcc
version 8.1.1
and compile the code as g++ -std=c++11
. 我正在使用
gcc
版本8.1.1
,并将代码编译为g++ -std=c++11
。
Although, if I move the definition of function Print
under the definition of struct Printer
(ie making it inline implicitly), the compiler does not produce any error. 虽然,如果我将函数
Print
的定义移到struct Printer
的定义下(即使其隐式内联),则编译器不会产生任何错误。
#include <iostream>
template <typename Type>
struct TestBase {
struct Printer {
template <typename T>
void Print(const T& t) {
std::cout << t << std::endl;
}
};
};
template <typename Type>
struct Test;
template<>
struct Test<int> : public TestBase<int> {
struct Printer : public TestBase<int>::Printer {
template <typename T>
void Print(int i, const T& t);
};
template <typename T>
void Printer::Print(int i, const T& t) {
std::cout << i << t << std::endl;
}
};
int main() {
Test<int> t;
}
UPDATE : 更新 :
Brian pointed out the exact reason why it is the case: "... A member function definition that appears outside of the class definition shall appear in a namespace scope enclosing the class definition..." Brian指出了这种情况的确切原因:“ ...出现在类定义之外的成员函数定义应出现在包含类定义的名称空间范围中……”
Brian not only answered the main question that started this topic but also an additional question that I asked in the comment to the accepted answer of him. Brian不仅回答了引发该主题的主要问题,而且还回答了我在评论中对他的公认答案所提出的其他问题。
[class.mfct]/1, emphasis mine: [class.mfct] / 1,重点是:
... A member function definition that appears outside of the class definition shall appear in a namespace scope enclosing the class definition.
...出现在类定义之外的成员函数定义应出现在包含类定义的名称空间范围内 。 ...
...
An enclosing class scope is thus not an allowed location for the definition. 因此,封闭类范围不是该定义的允许位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.