我有一个在 .h 文件中定义并在 .cc 文件中实现的虚拟 C++ 方法。应该将 .cc 文件中的实现标记为虚拟,还是仅标记 .h 文件中的声明?例如,我的标题有:
virtual std::string toString() const;
方法在我的.cc中实现:
std::string
MyObject::toString() const {
[implementation code]
}
应该将实现标记为虚拟,还是上面的代码可以?有关系吗?
最佳答案
C++ 标准 n3337 § 7.1.2/5 说:
The virtual specifier shall be used only in the initial declaration of a non-static class member function;
关键字 virtual
只能在类定义中使用,当您声明(或定义)方法时。所以...它可以在实现文件中使用,但如果它仍在类定义中。
例子:
class A {
public:
virtual void f();
};
virtual void A::f() {} // error: ‘virtual’ outside class declaration
// virtual void A::f() {}
int main() {
// your code goes here
return 0;
}
关于c++ - .cpp 文件中的虚拟 C++ 方法实现是否应该标记为虚拟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25797291/