我有一个类AP
template<typename T>
class AP : public std::auto_ptr<T>
{
typedef std::auto_ptr<T> Super;
public:
AP() : Super() { }
AP(T* t) : Super(t) { }
AP(AP<T>& o) : Super(o) { }
};
还有一个返回它的函数。
namespace AIR {
namespace Tests {
namespace
{
AP<A> CreateGraph()
{
AP<A> top(A::Create("xyz").release());
...
return top;
}
AP<A> top;
top = CreateGraph();
当我编译代码时
AP<A> top;
top = CreateGraph();
我收到了这个错误信息
no match for ‘operator=’ in ‘top = AIR::Tests::<unnamed>::CreateGraph()()’
我在 AP 类中添加了这个运算符,但它不起作用。
AP<T>& operator=(AP<T>& o) { (*(Super*)this) = o; return *this; }
类(class)有什么问题?
编辑
top.reset(CreateGraph().release())
解决了这个问题。
最佳答案
CreateGraph()
按值返回,因此 CreateGraph()
函数调用是右值。
因为 std::auto_ptr
复制赋值运算符通过非常量引用获取其参数,隐式声明的 AP
复制赋值运算符通过非常量引用获取其参数.
非常量引用只能绑定(bind)到左值,因此会出现错误。
正如我在 an answer to one of your previous questions 中解释的那样,如果你想要像 std::auto_ptr
一样的复制(实际的复制构造函数通过非常量引用获取它的参数),你还需要实现类似于 std::auto_ptr_ref
。
我解释了 std::auto_ptr
如何使用这个辅助类来允许在 How could one implement std::auto_ptr
's copy constructor? 的已接受答案中复制右值。
关于c++ - "no match for ‘operator=’ "g++ 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5253243/