【问题标题】:I am having trouble using an operator= overload with a static member function. Is there something wrong in the code?我在使用带有静态成员函数的 operator= 重载时遇到问题。代码有问题吗?
【发布时间】:2019-06-23 16:47:29
【问题描述】:

我有一个似乎工作正常的赋值运算符重载,我在一个指针类中定义了静态成员函数,它返回一个指针类型的类,它似乎也工作正常,但是当它们一起使用时,它甚至会引发转换错误尽管它们是同一类型。

例如

Pointer<float> a;
a = Pointer<float>::New(3.1415); //ERROR

所以当赋值运算符重载参数通过引用传递时它实际上工作正常,但是当我将它切换为按值传递时它会引发编译器错误。

//header
namespace Dexter {
template <class T>
class Pointer {
private:
    T* m_raw_pointer;
    bool m_is_owner;
public:

    Pointer();
    Pointer(T);
    ~Pointer();

    static Pointer<T> New(T);
    virtual void Delete();

    void operator=(Pointer<T>&);
    T operator*();
};
};

//implementation
template <class T> Dexter::Pointer<T> Dexter::Pointer<T>::New(T val) {
Pointer<T> temp(val);
temp.m_is_owner = false;
return temp;
}
template <class T> void Dexter::Pointer<T>::Delete() {

if (m_raw_pointer != NULL && m_is_owner) {
    delete m_raw_pointer;
    m_raw_pointer = NULL;
    m_is_owner = false;
}
}

template <class T> void Dexter::Pointer<T>::operator=(Pointer<T>& obj) {
Delete();

m_raw_pointer = obj.m_raw_pointer;
obj.m_is_owner = false;
m_is_owner = true;
}

//main.cpp
Dexter::Pointer<float> a(1.616);
a = Dexter::Pointer<float>::New(3.1415); //ERROR: conversion type

预期结果:

*a.m_raw_pointer = 3.1415;

实际结果:

Error C2679 binary '=': no operator found which takes a right-hand operand of type 'Dexter::Pointer&lt;float&gt;' (or there is no acceptable conversion) Dexter

【问题讨论】:

  • 请发布完整的错误信息。此外,operator = 通常应该接受对 const 对象的引用或对非 const 对象的右值引用,而您忘记提供复制/移动构造函数。
  • 你似乎在尝试重塑std::unique_ptr。你有什么理由不能使用真正的交易吗?

标签: c++


【解决方案1】:

您的 operator=(Pointer&lt;T&gt;&amp;) 通过非常量引用获取其参数,这意味着它不能接受临时引用。但Pointer&lt;float&gt;::New(3.1415) 实际上确实返回了一个临时的。

您似乎想要一个移动赋值运算符,而不是一个复制赋值运算符(因为您的修改了副本的来源)。这样的函数将通过右值引用 operator=(Pointer&lt;T&gt;&amp;&amp;)(注意两个 & 符号)获取其参数。

【讨论】:

    猜你喜欢
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多