我已将其作为作业的 .H 文件提供给我,我的任务是创建 .C 来配合它。这真的很简单,我敢肯定我错过了一些小东西。
#ifndef String_H
#define String_H
#include <iostream>
class String
{
public:
// constructor: initializes String with copy of 0-terminated C-string
String(const char *p);
// destructor (when can shared data be released?)
~String();
// copy constructor (how does this change reference counts?)
String(const String &x);
// assignment operator (how does this change reference counts?)
String &operator=(const String &x);
// return number of non-0 characters in string
int size() const;
// return reference count
int ref_count() const;
// returns pointer to character array
const char *cstr() const;
private:
// data containing character strings
// shared by Strings when copying/assigning
struct SharedCString
{
char *data; // 0-terminated char array
int n; // number of non-0 characters in string
int count; // reference count, how many Strings share this object?
};
SharedCString *shared;
};
#endif
在我的构造函数中,当我尝试将 SharedCString 的计数值设置为 1 时,出现分段错误。
我试图通过它使用:
shared->count = 1;
我不确定为什么这不起作用。