gpt4 book ai didi

c++ - Sean Parent : for polymorphic types in an inheritance hierarchy, 具有可变对象是极端的异常(exception)

转载 作者:行者123 更新时间:2023-12-03 10:05:16 25 4
gpt4 key购买 nike

我想知道 Sean Parent 实际上是什么意思
by this statement

for polymorphic types in an inheritance hierarchy, having mutable object is the extreme exception...



他接着提到了两个原因,但我无法理解他的解释。

是什么阻止我在子类中提供一个函数来实际改变这个对象的内部结构?

有人可以详细说明一下吗?

最佳答案

回答
在研究了一个小时的视频后 - 我明白了他的意思。
在 47:49,他开始说:

Do we actually modify this object - and the internals of it? An observation is that for polymorphic use cases of objects - having mutable objects - is the extreme, extreme exception where there is benefit for that. And there's a good reason why. So if I have a virtual function that's mutating my object - OK? - Then, what I am doing is one of two things. I'm either saying that my sub-classes can provide a different implementation, which that very problematic because that's going to change the performance guarantees of that operation and potentially a bunch of other operations on my object or I'm saying that my subclasses want to observe when this thing is set but they're not actually mutating it so rather than having them override my mutating virtual functions what I should do is provide an observer function where I will call them when I have changed things...


他是字面意思。

...have a virtual function that's mutating my object...


因此,他说你很少有像......
Animal
+-Cat
+-Dog
| +-Doberman
+-Bird
...您想使用具有不同实现的虚拟方法更改不同多态变体的状态(变异)。
例如。
int main() {

Animal* apObject[] = { new Cat(), new Dog(), new Doberman() };

const int cnAnimals = sizeof(apObject)/sizeof(Animal*);
for ( int i = 0; i < cnAnimals; i++ ) {
apObject[i]->Feed(1.3);
}
for ( int i = 0; i < cnAnimals; i++ ) {
delete apObject[i];
}
return 0;
}
所有动物都通过应用多态函数(“Feed”)来获取食物,但不同的实现以不同的方式修改状态。
他说这是极端的,极端的很少!
我的评论
Sean Parent 在使用复制构造函数和赋值运算符复制多态对象时遇到了问题。如果对象不可变,他似乎在这里提供了一个很好的解决方案。
然而,我认为肖恩 parent 声明 “对象的多态用例 - 具有可变对象 - 是极端极端的异常(exception)” 错了 .
背景:
Why do we need virtual functions in C++?
引自《呆伯特原则》:

ENGINEER IDENTIFICATION GUIDE

Self Assessment

You walk into a room and notice that a picture is hanging crooked.

You...

A: Straighten it.

B: Ignore it.

C: Buy a CAD systemand spend the next six months designing a solar-powered,self-adjusting picture framewhile often stating aloudyour belief that
the inventor of the nail was a total moron.

The correct answer is “C” but partial credit can be given to anybody who writes “It depends” in the margin of the test or simply blames the whole stupid thing on “Marketing.”


他的视频中有更多的陈述,我不同意——出于同样的原因。

关于c++ - Sean Parent : for polymorphic types in an inheritance hierarchy, 具有可变对象是极端的异常(exception),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48559050/

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