gpt4 book ai didi

c++ - 为什么较新版本的 C++ 不允许在类声明中定义纯方法?

转载 作者:太空宇宙 更新时间:2023-11-04 15:13:06 26 4
gpt4 key购买 nike

为什么 MSVC++ 2015 及其早期版本允许在类声明中定义纯虚方法 但在 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 ]

关于c++ - 为什么较新版本的 C++ 不允许在类声明中定义纯方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46384296/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com