在学习C++Primer第13章时,定义的类Spring代码如下:
#ifndef STRING_H
#define STRING_H
#include <memory>
#include <cstring>
#include <algorithm>
#include <iostream>
class String {
friend String add(const String&, const String&);
public:
// constructor
String(): sz(0), p(nullptr) { }
String(const char *cp): sz(std::strlen(cp)), p(alloc.allocate(sz))
{ std::uninitialized_copy(cp, cp + sz, p); }
// copy control
String(const String&);
String& operator=(const String&);
~String();
private:
static std::allocator<char> alloc;
void free();
size_t sz;
char *p;
};
String::String(const String &s): sz(s.sz), p(alloc.allocate(s.sz)) {
std::uninitialized_copy(s.p, s.p + s.sz, p);
std::cout << "String(const String&);" << std::endl;
}
void String::free() {
if (p) alloc.deallocate(p, sz);
}
String::~String() { free(); }
String& String::operator=(const String &rhs) {
auto newp = alloc.allocate(rhs.sz);
std::uninitialized_copy(rhs.p, rhs.p + rhs.sz, newp);
free();
p = newp;
sz = rhs.sz;
std::cout << "String& operator=(const String&);" << std::endl;
return *this;
}
String add(const String &s1, const String &s2) {
String newStr;
newStr.p = String::alloc.allocate(s1.sz + s2.sz);
newStr.sz = s1.sz + s2.sz;
std::uninitialized_copy(s2.p, s2.p + s2.sz,
std::uninitialized_copy(s1.p, s1.p+s1.sz, newStr.p));
return newStr;
}
#endif
然而,在用如下代码调试时始终报错:
#include <vector>
#include "String.h"
int main()
{
std::vector<String> vec;
String s1("Hello");
String s2("World");
vec.push_back(s1);
vec.push_back(s2);
return 0;
}
报错内容为:
C:\Users\ADMINI~1\AppData\Local\Temp\cchmbeUn.o 13-48.cpp:(.rdata$.refptr._ZN6String5allocE[.refptr._ZN6String5allocE]+0x0): undefined reference to `String::alloc'
E:\Programming\C & C++\CppPrimer\CppPrimer\3rd Part\collect2.exe [Error] ld returned 1 exit status
然而String.h文件可以编译通过,不理解错误在哪里,求教。谢谢。