gpt4 book ai didi

C++ 方法覆盖

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:23:17 25 4
gpt4 key购买 nike

维基百科示例位于 this关于 C++ 中方法重写的文章是否正确?

请看下面我提到注释的代码//INCORRECT

对 C++ 中的覆盖和运行时多态性有点困惑。这个 Actor 应该做什么?

#include <iostream>

class Rectangle {
public:
explicit Rectangle(double l, double w) : length(l), width(w) {}
virtual void print() const;

private:
double length;
double width;
};

void Rectangle::print() const { // print() method of base class
std::cout << "Length = " << this->length << "; Width = " << this->width;
}

class Box : public Rectangle {
public:
explicit Box(double l, double w, double h) : Rectangle(l, w), height(h) {}
virtual void print() const; // virtual is optional here, but it is a good practice to remind it to the developer

private:
double height;
};

void Box::print() const { // print() method of derived class
Rectangle::print(); // Invoke parent print() method.
std::cout << "; Height= " << this->height;
}

int main(int argc, char** argv) {
Rectangle rectangle(5.0, 3.0); rectangle.print();
// outputs:
// Length = 5.0; Width = 3.0

Box box(6.0, 5.0, 4.0);
// the pointer to the most overridden method in the vtable in on Box::print
//box.print(); // but this call does not illustrate overriding

static_cast<Rectangle&>(box).print(); // this one does

// outputs:
// Length = 5.0; Width = 3.0; Height= 4 // INCORRECT

//But it actually outputs Length = 6; Width = 5; Height = 4

getchar();
return 0;

}

最佳答案

你是对的 - 提到的输出是不正确的。

转换简单地演示了一个盒子是一种矩形(继承自它)并且即使作为一个矩形,方法覆盖仍然有效并且 Box 版本print 方法将被调用。

关于C++ 方法覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9065200/

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