【发布时间】:2016-09-01 20:47:58
【问题描述】:
我希望派生的 ClassA 具有返回 ClassA 的全新对象的方法。我收到关于返回对本地对象的引用的编译器警告。
有人建议我需要实现一个移动构造函数。该怎么做?
不起作用的代码:
#include <iostream>
using namespace std;
template <typename T>
class AbstractClass {
public:
virtual AbstractClass<T>& operator[](int index) = 0;
} ;
template <typename T>
class ClassA : public AbstractClass<T> {
public:
ClassA<T>& operator[](int index){
ClassA<T> A;
return A;
}
ClassA(ClassA && c){
//move constructor that doesn't work.
}
} ;
template <typename T>
class ClassB : public ClassA<T> {
public:
ClassA<T>& operator[](int index){
ClassA<T> A;
return A;
}
} ;
int main(void){
ClassA<int> A;
A[0][1][2];
}
错误信息(intel icc):
test2.cpp(15): error: copy constructor for class "ClassA<T>" may not have a parameter of type "ClassA<T>"
ClassA(ClassA && c){
^
另一个版本:
#include <iostream>
using namespace std;
template <typename T>
class AbstractClass {
public:
virtual AbstractClass<T> operator[](int index) = 0;
} ;
template <typename T>
class ClassA : public AbstractClass<T> {
public:
ClassA<T>() {}
ClassA<T> operator[](int index){
ClassA<T> A;
return A;
}
} ;
template <typename T>
class ClassB : public ClassA<T> {
public:
ClassA<T> operator[](int index){
ClassA<T> A;
return A;
}
} ;
int main(void){
ClassA<int> A;
A[0][1][2];
}
错误(英特尔 icc):
test2.cpp(12): error: return type is neither identical to nor covariant with return type "AbstractClass<int>" of overridden virtual function "AbstractClass<T>::operator[] [with T=int]"
ClassA<T> operator[](int index){
^
detected during instantiation of class "ClassA<T> [with T=int]" at line 26
test2.cpp(26): error: object of abstract class type "ClassA<int>" is not allowed:
pure virtual function "AbstractClass<T>::operator[] [with T=int]" has no overrider
ClassA<int> A;
^
test2.cpp(12): error: function returning abstract class "ClassA<int>" is not allowed:
pure virtual function "AbstractClass<T>::operator[] [with T=int]" has no overrider
ClassA<T> operator[](int index){
^
detected during instantiation of "ClassA<T> ClassA<T>::operator[](int) [with T=int]" at line 27
test2.cpp(13): error: object of abstract class type "ClassA<int>" is not allowed:
pure virtual function "AbstractClass<T>::operator[] [with T=int]" has no overrider
ClassA<T> A;
^
detected during instantiation of "ClassA<T> ClassA<T>::operator[](int) [with T=int]" at line 27
compilation aborted for test2.cpp (code 2)
【问题讨论】:
-
我在堆栈溢出和谷歌中查找了它。有些页面提到了移动构造函数,但很少有页面讨论模板移动构造函数。如果我知道它为什么不起作用,我不会问。
-
添加您在问题中使用的编译器
-
英特尔 icc。好吧。我刚刚找到“stackoverflow.com/questions/11028929/…”所以他们建议的“解决方案”实际上是行不通的。
-
operator[]应该怎么做?您的意思是返回*this?请使用 C++11 标准编译。你需要在移动构造函数旁边声明ClassA() = default;。 -
混合多态性和模板时,您需要确定自己在做什么。即使作为示例,这段代码看起来也被过度设计了。
标签: c++ templates abstract-class