您好,以下程序适用于 g++ 4.9.2 (Ubuntu 4.9.2-10ubuntu13),但函数 get
需要 virtual
关键字:
//g++ -std=c++14 test.cpp
//test.cpp
#include <iostream>
using namespace std;
template<typename T>
constexpr auto create() {
class test {
public:
int i;
virtual int get(){
return 123;
}
} r;
return r;
}
auto v = create<int>();
int main(void){
cout<<v.get()<<endl;
}
如果我省略 virtual
关键字,我会收到以下错误:
test.cpp: In instantiation of ‘constexpr auto create() [with T = int]’:
test.cpp:18:22: required from here
test.cpp:16:1: error: body of constexpr function ‘constexpr auto create() [with T = int]’ not a return-statement
}
^
如何在不使用 virtual
关键字的情况下让上面的代码工作(使用 g++)?
最佳答案
在函数内部定义的类不能在函数外部访问。
我的建议是:在函数外声明 test
并向 get
函数添加 const
限定符。
#include <iostream>
using namespace std;
class test {
public:
int i;
int get() const {
return 123;
}
};
template<typename T>
constexpr test create() {
return test();
}
auto v = create<int>();
int main(void){
cout<<v.get()<<endl;
}
关于c++ - 从 constexpr 函数返回一个类需要使用 g++ 的 virtual 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32806405/