【问题标题】:Problems overloading operator "=" in template模板中重载运算符“=”的问题
【发布时间】:2013-05-08 22:29:00
【问题描述】:

我从之前分配的序列类中获得了这段代码,并且应该将其转换为带有节点类的模板。我的所有其他函数似乎都可以正常工作,但是这个重载运算符的措辞或语义似乎有问题。这是我的代码:

template <class sequence, class Item>
void operator =(const sequence source)
{

if (this == &source)

{

    return;

}

list_clear(head_ptr);

many_nodes = 0;

list_copy(source.head_ptr, head_ptr, tail_ptr);

start();

for (node *ptr=source.head_ptr; ptr != source.cursor; ptr = ptr->link())

{

    advance();

}

many_nodes = source.many_nodes;

}

这是我得到的错误:6\sequence4.template(152): error C2801: 'main_savitch_6B::operator =' must be a non-static member

第 152 行是函数的右大括号。

我确实在网站上搜索了答案并尝试了一些修复,但似乎都没有奏效。

谢谢大家,感谢大家的帮助!

【问题讨论】:

  • 从发布的 sn-p 中看不出operator = 是否确实是某个类的非静态成员函数。
  • 是类声明里面的定义吗?显示整个代码。请缩进。
  • 和模板参数Item不能被隐式推断。

标签: c++ templates operator-overloading


【解决方案1】:

我认为您的 operator= 的签名不正确。我认为通常你必须有这样的东西:

Sequence & operator=(const Sequence & rhs){
if (&rhs != this){
// Your stuff ...
}
return *this;
}

【讨论】:

  • Sequence&amp; Sequence::operator=(const Sequence &amp; rhs)
【解决方案2】:

您似乎被要求创建一个Sequence 类,以Item 为模板,并且Sequence 类有一个赋值运算符。在这种情况下,语法将是。

template< class Item >
class Sequence
{
    Sequence& operator=( Sequence const& rhs )
    {
        ...
    }
...
};

或者我可能误解了这个问题。

【讨论】:

    猜你喜欢
    • 2011-06-11
    • 2015-01-18
    • 1970-01-01
    • 2011-04-22
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    • 2022-10-01
    • 2016-04-04
    相关资源
    最近更新 更多