在C++中调用母类operator=的常见方法?
假设我有一个 Dog 类,它继承自 Animal 类, 您可能想在 Dog::operator= 中插入对 Animal::operator= 的调用。
最易读/最常见的编写方式是什么?
我想我认识那两个……
static_cast<Animal*>(this)->operator=(other);
而且
this->Animal::operator=(other);
Let's suppose I have a class Dog that inherits from class Animal,
you might want to insert a call to Animal::operator= in Dog::operator=.
What is the most readable/common way to write it?
I think I know those two...
static_cast<Animal*>(this)->operator=(other);
and
this->Animal::operator=(other);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您是在子类方法中执行此操作,因此
不需要
this->
。范围解析语法完全按照要求执行。我不认为通过强制转换“间接”进行此操作有什么意义。另请注意,在一般情况下,使用强制转换执行此操作可能不会产生预期结果,因为它不会禁用虚拟方法调用的动态解析。 (顺便说一句,赋值运算符可以声明为虚拟)。这样做的一个明显后果是,使用虚拟方法时,“cast”变体可能很容易导致无限递归。
Since you are doing it from within a child class method
No need for
this->
. The scope resolution syntax does exactly what was requested. I don't see a point in doing it "indirectly" with a cast.Note also that doing it with a cast might not produce the expected result in general case, since it will not disable the dynamic resolution of virtual method call. (And, BTW, assignment operator can be declared virtual). An obvious consequence of that is that with virtual methods the "cast" variant might easily result in endless recursion.
this->Animal::operator=(other);
是正确的方法,您完全限定了引用父实现的方法,您不需要为此进行强制转换,这使得代码更难阅读。this->Animal::operator=(other);
is the correct way, you fully qualify the method referring to your parent implementation, you don't need to cast yourself for that and it makes the code harder to read.