Ben*_*ang 4 c++ polymorphism templates operator-overloading friend
背景
我正在从这门课程中自学 C++ 。我正在尝试使用友元函数(作业 4.2)重载类中的运算符。
编辑
链接的问题没有回答我的问题。该问题的公认解决方案提供了一种在 header + cpp 文件中实现模板的方法(并非全部在同一个文件中)。
事实上,我已经咨询了这个问题,以部分地提出我的情况。
我的尝试
使用方法 2,我几乎可以让我的代码工作(请参阅神秘的错误消息)。事实证明我缺少一个<>. (解决方案手册)。
我试过谷歌搜索,但没有其他人有这种情况
同时。
我的理由
不应使用类公共函数进行运算符重载,因为调用该函数的对象将被隐式传递,占用一个函数参数。让重载运算符对称(在用法和定义上)是更好的代码风格。
的用法friend是由讲义建议的。
题
<>需要?谢谢你。
代码
堆栈.h
#include <iostream>
#include <vector>
using std::cout;
using std::vector;
template <typename T>
class Stack;
template <typename T>
Stack<T> operator+(Stack<T> a, Stack<T> b);
template <typename T>
class Stack { // use default constructors and destructors
private:
vector<T> s;
public:
bool empty();
void push(const T &item);
T& top();
void pop();
friend Stack<T> operator+(Stack<T> a, Stack<T> b); // need operator+<>
};
Run Code Online (Sandbox Code Playgroud)
堆栈文件
#include <iostream>
#include <vector>
using std::cout;
#include "stack.h"
template <typename T>
bool Stack<T>::empty() {
return s.empty();
}
template <typename T>
void Stack<T>::push(const T &item) {
s.push_back(item);
}
template <typename T>
T& Stack<T>::top() {
return s.back();
}
template <typename T>
void Stack<T>::pop() {
s.pop_back();
}
template <typename T>
Stack<T> operator+(Stack<T> a, Stack<T> b) {
Stack<T> temp;
while (!b.empty()) {
temp.push(b.top());
b.pop();
}
while (!a.empty()) {
temp.push(a.top());
a.pop();
}
Stack<T> c;
while (!temp.empty()) {
c.push(temp.top());
temp.pop();
}
return c;
}
int main() {
Stack<int> a, b;
a.push(1);
a.push(2);
b.push(3);
b.push(4);
Stack<int> c = a + b;
cout << c.top() << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
错误信息
Undefined symbols for architecture x86_64:
"operator+(Stack<int>, Stack<int>)", referenced from:
_main in stack-d2f02a.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1
Run Code Online (Sandbox Code Playgroud)
您需要添加<>(或<T>) 以使友元声明引用声明的运算符模板。没有那个朋友声明将声明一个非模板operator+未定义,这就是您收到链接器错误的原因。
顺便说一句:您还可以像这样明确指定模板参数
// refers to the instantiation of template operator+ for T
friend Stack<T> operator+<T>(Stack<T> a, Stack<T> b);
// ^^^
Run Code Online (Sandbox Code Playgroud)
当使用<>模板参数时T会从函数参数中推导出来,并具有相同的效果。
// refers to the instantiation of template operator+ for T
// T is deduced from function parameters
friend Stack<T> operator+<>(Stack<T> a, Stack<T> b);
// ^^
Run Code Online (Sandbox Code Playgroud)