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

C+ how to change array of chars in function

本文关键字:字符 数组 函数 何更改 C++      更新时间:2023-10-16

我有这个标题:

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

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

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

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[]),而不知道输入缓冲区的长度;这不是一个好的场景。