fd_lrh 2016-01-16 14:47 采纳率: 0%
浏览 1658

C++Primer,定义的String类的问题

在学习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文件可以编译通过,不理解错误在哪里,求教。谢谢。

  • 写回答

3条回答 默认 最新

  • threenewbee 2016-01-16 14:56
    关注

    String::alloc没有定义,你在哪里定义的。

    评论

报告相同问题?

悬赏问题

  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题