为什么较新版本的 C++ 不允许在 class 声明中定义纯方法?
Why newer versions of C++ don't allow definition of pure method inside class declaration?
为什么 MSVC++ 2015 及其早期版本允许在 class 声明中定义 pure virtual method
但在 GCC 4.9
上,我猜 MSVC++ 2017
不允许这样:
#include <iostream>
class A{
public:
virtual void Foo() = 0;
};
class B: public A {
public:
virtual void Foo() = 0 { std::cout << "B::Foo()" << std::endl;
}; // Allowed on MSVC 2015 and old versions
//virtual void Foo() = 0; // on newer versions
};
//void B::Foo(){
// std::cout << "B::Foo()" << std::endl;
//} // Ok here!
class C : public B{
public:
void Foo(){
B::Foo();
std::cout << "C::Foo()" << std::endl;
}
};
int main(){
// A aObj; // error
// B bObj; // error
C cObj; // correct
cObj.Foo();
std::cout << std::endl;
std::cin.get();
return 0;
}
standard 明确提到这是不允许的(例如 C++14,§10.4./2)
A function declaration cannot provide both a pure-specifier and a
definition — end note ] [ Example: struct C { virtual void f() = 0 {
}; // ill-formed }; — end example ]
为什么 MSVC++ 2015 及其早期版本允许在 class 声明中定义 pure virtual method
但在 GCC 4.9
上,我猜 MSVC++ 2017
不允许这样:
#include <iostream>
class A{
public:
virtual void Foo() = 0;
};
class B: public A {
public:
virtual void Foo() = 0 { std::cout << "B::Foo()" << std::endl;
}; // Allowed on MSVC 2015 and old versions
//virtual void Foo() = 0; // on newer versions
};
//void B::Foo(){
// std::cout << "B::Foo()" << std::endl;
//} // Ok here!
class C : public B{
public:
void Foo(){
B::Foo();
std::cout << "C::Foo()" << std::endl;
}
};
int main(){
// A aObj; // error
// B bObj; // error
C cObj; // correct
cObj.Foo();
std::cout << std::endl;
std::cin.get();
return 0;
}
standard 明确提到这是不允许的(例如 C++14,§10.4./2)
A function declaration cannot provide both a pure-specifier and a definition — end note ] [ Example: struct C { virtual void f() = 0 { }; // ill-formed }; — end example ]