c++ - 模板类的重载赋值运算符

标签 c++ templates assignment-operator

我正在尝试重载 operator=(),但我收到了错误:没有可行的重载 '='。但我不明白为什么。我在这里错过了什么?我厌倦了 Overloading assignment operator in a class template that can cast to another template type 中的答案但是有人说要给返回类型的模板参数一个新类型......?这导致编译器为我提示未知类型。

template<typename T, typename P>
class SomeClass
{

public:

    SomeClass<T, P> operator=(SomeClass<T, P>& src)
    {
        if (this != &src)
        {
            vectorfield.resize(src.vectorfield.size());
            for (int i = 0; i < src.vectorfield.size(); ++i)
            {
                vectorfield[i] = src.vectorfield[i];
            }
        }
        return *this;
    }

private:

    std::vector<std::vector<std::string>> vectorfield;
};



template<typename SC>
class SomeOtherClass
{

public:

    typedef SC someclass_type;

    void func()
    {
       sc = someclass_type();
    }

private:
    someclass_type sc;
};


int main()
{

    typedef SomeClass<int, int> SCII;
    typedef SomeOtherClass<SCII> SOC_scii;

    SOC_scii soc_scii;
    soc_scii.func();


}

最佳答案

与临时工一起工作,例如

   sc = someclass_type();

赋值运算符的参数应该是一个const引用。

SomeClass<T, P>& operator=(const SomeClass<T, P>& src)
               ^           ^^^^^

赋值运算符通常还返回对赋值对象的引用(因此它可以用于链式赋值,如 a = b = c;)。按值返回会创建一个额外的拷贝,我们可能不希望这样。

关于c++ - 模板类的重载赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32985287/

相关文章:

c++ - 使用enable_if仅匹配具有特定静态数据成员且仅具有特定值的类

c++ - (特别是显式的)特化中模板参数列表的访问检查规则

c++ - 试图理解 auto_ptr

c# - 为什么短原语有赋值运算符(&=、+=)但没有非赋值运算符(&、+)?

c++ - std::move(T&&) 和临时对象。临时从哪里来?

c++ - OpenCV : undefined reference to imread()

django - 如何检查是否在django模板中选中了复选框

c++ - 为什么我不能有一个纯虚拟赋值运算符?

c++ - 将 C++ 与 BLAS 和 LAPACK 链接起来

c++ - Windows系统加入Azure AD时获取登录用户的UserPrincipalName