2

嗨,以下程序适用于 g++ 4.9.2(Ubuntu 4.9.2-10ubuntu13),但该virtual函数需要关键字get

//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++)?

4

1 回答 1

0

函数内部定义的类不能在函数外部访问。我的建议是:test在函数外部声明并在函数中添加const限定符get

#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;
}
于 2015-09-27T09:49:59.683 回答