通过提及对象本身返回对象字段

时间:2013-06-19 11:00:37

标签: c++

我想从“string.h”(STL)创建一个类似“string”的类。 我的班级是:

class MyChar
{
 char *Buff;
 public:

 /* Some constructors and other helpful methods */

};

我的问题是,我不知道如何做以下事情:

#include <iostream>
int main()
{

 MyChar str;
 str = "My new string";
 cout << str;

}

我不想提及“str.Buff”或“str.getBuffer()”或其他东西......只是“str”。就像“字符串”类一样。

4 个答案:

答案 0 :(得分:1)

如果你想使用你的类,你需要所谓的“赋值运算符”。维基百科有一篇非常好的文章here.

基本上你要做的是将右侧(字符数组)分配到左侧(您的类实例)。您需要重载=运算符,或者像评论所说的那样,<<运算符。

编辑:由于OP因为没有“正确”回答他的模糊问题而低估了我,所以这是一个<<重载的片段:

std::ostream& operator<<(std::ostream& out, const MyChar& buf) {
    out << buf.Buf;
    return out;
}

你会像这样使用它:

std::cout << MyChar << std::endl;

当然,你的类现在有很多问题要发生,即你没有为字符数组分配数组空间,祝你好运!

答案 1 :(得分:1)

您需要实现正确的构造函数和赋值运算符。在这种情况下,以const char*为参数的变体。您还需要重载输出操作符。

肯定需要了解the rule of three和动态内存管理。

答案 2 :(得分:1)

您需要为您的类重载赋值运算符=和ostream运算符<<。我发现的一篇好文章是here

答案 3 :(得分:-1)

你需要添加这样的东西:[未经过测试,但会给你一个想法]

void operator=(const char *str )
{ 
    strcpy(Buff,feet, str);

}

以下内容应该在课程定义之外。

ostream& operator<<(ostream& os, const MyChar& mch)
{
    os << mch.Buff;
    return os;
}

将以下语句添加到您的班级。 朋友ostream&amp;运算符&lt;&lt;(ostream&amp; os,const MyChar&amp; mch);