运算符的虚拟超定义=

Virtual surdefinition of operator =

本文关键字:定义 虚拟 运算符      更新时间:2023-10-16

我有两个类,我想对运算符=进行surdefine。

class Composant {
string description;
...
virtual const Composant& operator=(const Composant &c)
{
    description = c.description;
    return *this;
}
}

另一个继承了:

class Ecran : Composant {
int format, pitch;
double taille;
...
const Ecran& operator=(const Ecran &e)
{
    format = e.format;
    taille = e.taille;
    pitch = e.pitch;
    //traiter composant
    Composant::operator=(e);
}

主要代码示例:

Composant *p=new Ecran(.....);
Composant *t=new Ecran(.....);
(*p)=*t;

这是正确的方法吗?

我假设我们必须将运算符=的surdefinition放在虚拟中,每次我们都有这种类型的继承,那么?运算符==也是如此。。。

这是正确的方法吗?

没有虚拟调度进入:

(*p)=*t;

您只是在呼叫Composant::operator=。这是否是正确的方法取决于你想要实现的目标。

可以定义虚拟operator=,但不推荐使用。

const Ecran& operator=(const Ecran &e)
{
    format = e.format;
    taille = e.taille;
    pitch = e.pitch;
    //traiter composant
    Composant::operator=(e);
}

必须返回值

return *this;

(*p)=*t;调用Composant类的operator=而不是Ecran类,因为这在Composant上操作。您可以定义

virtual const Composant& operator=(const Composant &c);

Ecran类中,它将被调用,但它将无法访问运算符右侧的Ecran成员。