考虑:
// in header.h
class A {
public:
virtual ~A() = 0;
};
class B : public A {
public:
~B() override {}
}
Run Code Online (Sandbox Code Playgroud)
链接器报告无法解析:
外部符号"public:virtual __thiscall A ::〜(void)"在函数"public:virtual __thiscall B :: ~B(void)"中引用
我发现我必须写出定义A::~A()
.
我曾经认为纯虚拟类定义了接口(函数声明),并且它们不必包含函数定义.我应该为纯虚基类中的所有虚函数编写定义吗?或者我应该只需要编写析构函数?
我正在尝试编写自己的向量模板类,但是在编写友元函数声明时遇到了一些问题。
一开始我是这样写的:
template <typename T, typename Alloc = std::allocator<T>>
class vector {
public:
friend bool operator==(const vector<T, Alloc>&, const vector<T, Alloc>&);
};
Run Code Online (Sandbox Code Playgroud)
但是编译器报告了一个警告,我声明了一个非模板函数。所以我把朋友声明改成了这样:
template <typename T, typename Alloc = std::allocator<T>>
class vector {
public:
template <typename E, typename F>
friend bool operator==(const vector<E, F>&, const vector<E, F>&);
};
Run Code Online (Sandbox Code Playgroud)
到目前为止一切都很好,但我认为仍然存在问题。如果我这样写,我会创建所有operator==
将两个模板参数作为其友元函数的函数。例如,operator==(const vector<int>&, const vector<int>&)
andoperator==(const vector<double>&, const vector<double>&)
都是vector<int>
的友元函数。
在模板类中编写友元函数的正确方法是什么?