C +如何在函数中更改字符数组

时间:2015-12-13 18:23:16

标签: c++ pointers

我有这个标题:

MvProjectQueue & operator >> (char *);

我必须编写符合此规范的功能。 (我的函数应该使用>>运算符)“返回”一个字符数组

我必须更改传递的参数,即在调用函数时我得到一个char数组,我必须修改它(就地)。

通常我会用

MvProjectQueue & operator >> (char **);

有一个指向char *的指针,我会轻易解决它,使用类似的东西:

#include <iostream>

using namespace std;

class SimpleShowcaseObject
{
public:
    SimpleShowcaseObject(){};
    ~SimpleShowcaseObject(){};

    SimpleShowcaseObject & operator >> (char ** p_ch)
    {
        *p_ch = "changed";
        cout << "in scope: " << *p_ch << endl;

        return *this;
    }
};

int main(void)
{
    char *ch = new char[10];

    ch = "hello";
    SimpleShowcaseObject o = SimpleShowcaseObject();

    cout << "original: " << ch << endl;
    o >> &ch;
    cout <<"changed: " << ch << endl;

    delete[] ch;

    cin.get();
    return 0;
}

但是这个:

#include <iostream>

using namespace std;

class SimpleShowcaseObject
{
public:
    SimpleShowcaseObject(){};
    ~SimpleShowcaseObject(){};

    SimpleShowcaseObject & operator >> (char *ch)
    {
        ch = "changed";
        cout << "in scope: " << ch << endl;

        return *this;
    }
};

int main(void)
{
    char *ch = new char[10];

    ch = "hello";
    SimpleShowcaseObject o = SimpleShowcaseObject();

    cout << "original: " << ch << endl;
    o >> ch;
    cout <<"changed: " << ch << endl;

    delete[] ch;

    cin.get();
    return 0;
}

执行并打印:

original: hello
in scope: changed
changed: hello

我希望

original: hello
in scope: changed
changed: changed

(编辑好几次,非常感谢大家帮忙!)

1 个答案:

答案 0 :(得分:0)

您的函数会收到您可以写入的缓冲区:

SimpleShowcaseObject & operator >> (char *ch)
{
    //ch = "changed";// with this you are changing the value of the pointer, not what you want
    strcpy (ch, "changed");
    cout << "in scope: " << ch << endl;

    return *this;
}

正如其他人已经指出的那样,这不是一个好设计:你的operator >>必须在缓冲区中写一个字符串(char[]),而不知道输入缓冲区的长度;不是一个很好的场景。