【发布时间】:2020-01-09 23:16:25
【问题描述】:
我不知道这段代码有什么问题:
template <class T = char, int num = 100> class Stack;
template <class T = char, int num1 = 100, int num2 = 100> Stack<T, num1>& operator+=(Stack<T, num1>& s1, const Stack<T, num2>& s2);
template <class T, int num>
class Stack{
template <T, int num1, int num2 > friend Stack<T, num1>& operator+=(Stack<T, num1>& s1, const Stack<T, num2>& s2);
public:
...
private:
Entry* first;
class Entry{
...
}
void append(const Stack& s){
if(isEmpty()) first = &s;
else first->last().next = &s;
}
...
};
template <class T, int num1, int num2>
Stack<T, num1>& operator+=(Stack<T, num1>& s1, const Stack<T, num2>& s2){
s1.append(Stack<T, num2>(s2));
...
};
关键是我已经将班级的友谊设置为运营商,我仍然收到error: 'append' is a private member of 'Stack<char, 100>'所以我做错了什么,有人可以检查一下吗?
【问题讨论】:
-
考虑让
operator+成为Stack类的非静态成员,然后它可以访问append()而无需成为friend。就此而言,为什么不直接将append()逻辑移动到operator+中呢?或者更好的是,将operator+=添加到Stack类,然后让operator+(成员或其他成员)调用operator+=。拥有私人append()真的没有意义 -
auto z = x + y;会修改x是不寻常的! -
@aschepler 你说得对,我在找 +=
标签: c++ operator-overloading friend