操作>>对于一个char指针包装
问题描述:
,因为我不允许使用的std :: string对我使用所谓的charstring类型为那些情况下,我不能初始化它自己的包装定制类的任务。操作>>对于一个char指针包装
类看起来是这样的:
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[]
而不是malloc
和free
。
我想我需要把这个在我的charstring类型结构,但这种藏汉给我的错误:'当我使用这两个参数不能只超载或'这个操作符function'太多的参数使用IStream的时候返回类型alone'区分功能。 – IMarks
这应该是一个朋友功能,而不是一个成员函数。确保在课堂外声明它,然后在课堂内为它添加一个朋友声明。 – templatetypedef