首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C++错误运算符:‘C2801 =’必须是非静态成员

C++错误运算符:‘C2801 =’必须是非静态成员
EN

Stack Overflow用户
提问于 2012-06-24 03:34:29
回答 3查看 5.1K关注 0票数 2

我正在尝试在模板类中重载operator=

我有这个模板类:

代码语言:javascript
复制
template <class T>
class Matrice
{
    T m,n;
public:
    template <class V>
    friend Matrice<V>& operator=(const Matrice<V> &);
};

template <class T>
Matrice<T>& Matrice<T>::operator=(const Matrice<T> &M)
{
    /*...*/
    return *this;
}

我也试过了:

代码语言:javascript
复制
template <class T>
class Matrice
{
    T m,n;
public:
    template <class V>
    Matrice<V>& operator=(Matrice<V> &);
};

template <class T>
Matrice<T>& operator=(Matrice<T> &M)
{
    /*...*/
    return *this;
}

但是我仍然得到这个错误:

代码语言:javascript
复制
error C2801: 'operator =' must be a non-static member
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-06-24 03:38:38

错误运算符:‘C2801 =’必须是非静态成员

粗体的词是这里的关键。friend不是会员,而是朋友。删除该friend关键字并将operator=视为成员:

语法上正确的版本是:

代码语言:javascript
复制
template <class T>
class Matrice
{
    T m,n;
public:
    template <class V>
    Matrice<V>& operator=(const Matrice<V> &);
};

template <class T>
template <class V>
Matrice<V>& Matrice<T>::operator=(const Matrice<V> &M)
{
    /*...*/
    return *this;
}

尽管我认为在那里使用该template <class V>是错误的;语义上正确的版本应该是

代码语言:javascript
复制
template <class T>
class Matrice
{
    T m,n;
public:
    Matrice<T>& operator=(const Matrice<T> &);
};

template <class T>
Matrice<T>& Matrice<T>::operator=(const Matrice<T> &M)
{
    /*...*/
    return *this;
}

说明:您通常不希望以这种方式将 Type<V>分配给Type<T>;如果您必须这样做,那么这可能是糟糕设计的标志。

票数 5
EN

Stack Overflow用户

发布于 2012-06-24 03:44:01

标准上说

12.8复制和移动类对象 class.copy

..。

17用户声明的复制赋值运算符X::operator=是类X的非静态非模板成员函数,它只有一个参数,类型为X、X&、常量X&、易失性X&或常量易失性X&。

好友函数不能满足这些要求。它必须是成员函数。

为了解决这只是“普通”赋值,而不是复制赋值的评论,让我们从标准中添加另一个引用:

13.5.3 Assignment over.ass

赋值运算符应该由只有一个参数的非静态成员函数实现。

在标准语言中,“应当”不会留下任何其他选项。

票数 3
EN

Stack Overflow用户

发布于 2012-06-24 03:49:00

您混合了朋友和成员的声明和定义:在第一个示例中,您将operator=声明为朋友,但将其定义为类成员。在第二个示例中,您将operator=声明为成员,但尝试将其定义为非成员。您的operator=必须是成员(请参阅this question为什么),并且您可以执行以下操作:

代码语言:javascript
复制
template <class T>
class Matrice
{
    T m,n;
public:
    Matrice<T>& operator=(Matrice<T> &);
};

template <class T>
Matrice<T>& Matrice<T>::operator=(Matrice<T> &M)
{
    /*...*/
    return *this;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11172389

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档