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没有定义,你在哪里定义的。

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!