我希望派生的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];
}
错误(intel 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)
答案 0 :(得分:1)
至少你在以下部分有错误:
ClassA<T>& operator[](int index){
ClassA<T> A; // <-- this variable will be destroyed
return A; // and you return a reference to A
}
返回值是对时间变量A
的引用,它将在执行[]
运算符后被销毁。
我建议你先解决这个错误。
此外,您没有任何初始化类的构造函数。
使用一些初始化的构造函数,例如
ClassA<T>() {}
使用gnu
和clang