运算符 >> 用于字符指针包装器

Operator >> for a char pointer wrapper

因为不允许我使用 std::string 进行赋值,所以我使用一个名为 CharString 的自定义 class 作为我无法自己初始化的情况的包装器。

class 看起来像这样:

struct CharString {
    char* str;
    CharString() : str() {}  // Initialize NULL
    ~CharString() { free(str); }
    // Conversions to be usable with C functions
    operator char**() { return &str; }
    operator char*() { return str; }
};

但是当我想在上面使用 >> 时出现以下错误。

binary '>>': no operator found which takes a right-hand operand of type 'utils::CharString' (or there is no acceptable conversion).

如何重载运算符 >>

CharString operator>>(std::istream& is) {
    is >> str;
    return *this;
};

我尝试了上面的方法,但仍然出现同样的错误。

重载流提取运算符的一般方法是提供具有以下一般形式的友元函数:

istream& operator>> (istream& in, MyObjectType& object) {
    // read all the data you need to construct an object.
    //
    // Then:
    if (in) { // Read succeeded! Update object.
        // Build a new object of the appropriate type.
        MyObjectType theOneIRead(basedOnTheDataIRead);

        // Swap the object you were given as input for the one you
        // just read. This way, if the read completely succeeds, you
        // update the rhs, and if the read failed, nothing happens.
        std::swap(object, theOneIRead);
    }
    return in;
}

请注意,此函数的签名将与您编写的不同。

您需要处理与从流中一次读取一个字符相关的逻辑,并构建某种临时缓冲区来保存它们。这不是微不足道的,也是我们有一个 std::string 类型与库打包在一起的原因之一。但除此之外,按照下面的模板应该可以满足您的需求。

独立地 - 您的结构当前具有析构函数,但没有复制构造函数、移动构造函数或赋值运算符。通常,您还希望与析构函数一起实现这些函数,因为否则复制对象将最终对指针进行浅表复制,并在两个独立对象尝试释放同一个指针时导致内存问题。

此外,由于这是 C++,请考虑使用 new[]delete[] 而不是 mallocfree