如何在函数中使用类因子

How can I use class factor in function?

本文关键字:函数      更新时间:2023-10-16
void Str::operator=(char* a)
    {
        delete[] str;
        len = strlen(a);
        str = new char[len + 1];
        strcpy (str, a);
}
void Str::operator=(class Str a)
{
    delete[] str;
    len = strlen(a.str);
    str = new char[len + 1];
    strcpy(str, a.str);

}

这有点像类 Str。我在类 Str 中定义了"operator=(char *a(",我可以像这样在"main.cpp"中使用第一个:

Str a("Icecream");
a = "Caken";

并且运行良好。

但是我如何使用"运算符=(类 Str a("?

我试过这样:

Str c("Hamburger")l
c = a;

我期望c有a.i,e的信息,c不再是汉堡包信息。

但是当我编译这段代码时,c 确实有 but 调用错误的信息。

我如何使用'运算符=(类 Str a('?

你应该像这样声明它:

void Str::operator=(const Str& a)

赋值运算符需要引用其右操作数(因此&(,并且不对其进行修改(因此const(。