gpt4 book ai didi

c++ - operator = 的虚拟超定义

转载 作者:行者123 更新时间:2023-11-30 03:48:55 25 4
gpt4 key购买 nike

我有两个类,我想对运算符 = 进行超定义。

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;

这是正确的做法吗?

我假设我们必须将 operator = 的超定义放在虚拟中,每次我们有这种类型的继承时?运算符 == 等也是如此......

最佳答案

Is this the correct way to do it?

没有虚拟调度进入:

(*p)=*t;

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

可以定义一个虚拟的operator= but not recommended .

关于c++ - operator = 的虚拟超定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32921178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com