【发布时间】:2018-05-20 16:36:05
【问题描述】:
我正在尝试重载赋值运算符以允许将集合分配给 unordered_set。我遇到了麻烦,请帮忙。
set<int> operator=(unordered_set<int> us)
{
set<int> s;
for(auto val:us) { s.insert(val); }
return s;
}
我收到以下错误:
error: ‘std::set<int> operator=(std::unordered_set<int>)’ must be a nonstatic member function
set<int> operator=(unordered_set<int> us)
这个函数是全局函数,不知道为什么g++会认为是静态函数。作为一个愚蠢的解决方案,我在函数中添加了自动限定符。
set<int> auto operator=(unordered_set<int> us)
{
set<int> s;
for(auto val:us) { s.insert(val); }
return s;
}
我收到以下错误:
error: two or more data types in declaration of ‘operator=’
set<int> auto operator=(unordered_set<int> us)
任何想法如何解决这个问题?我曾尝试为此寻找解决方案,但徒劳无功。
【问题讨论】:
-
错误很明显:不能有非成员赋值运算符。即使它被允许,想想你对运算符重载的了解,或者read some good books about it,非成员二元运算符(如赋值)需要采用 两个 参数: , 和右手边。但是,它不允许分配。
标签: c++ operator-overloading unordered-set