gpt4 book ai didi

c++ - 如何用 C++ 中的引用替换指针?

转载 作者:IT老高 更新时间:2023-10-28 22:25:07 29 4
gpt4 key购买 nike

“我敢肯定有几十个同名的问题。其中很多是重复的。我的也可能是重复的,但我找不到任何问题。所以我试着让它变得非常简洁、简短和简单。 "

我有这样的层次结构:

class Shape {
public:
virtual void virtualfunc() { std::cout << "In shape\n"; }
};

class Circle: public Shape {
public:
void virtualfunc() { std::cout << "In Circle\n"; };
};

当我在指针的帮助下使用类时,函数会按预期调用:

int main() {
Shape shape_instance;
Shape* ref_shape = &shape_instance ;
Circle circle_instance;
Circle* ref_circle = &circle_instance;

ref_shape = dynamic_cast<Shape*> (ref_circle);
ref_shape->virtualfunc();
}

这里程序调用了派生类的virtualfunc(),结果自然是:In Circle

现在,我想摆脱指针,改用引用,并获得相同的结果。所以我对 main() 做了一些简单的修改,看起来像这样:

int main() {
Shape shape_instance;
Shape& ref_shape = shape_instance;
Circle circle_instance;
Circle& ref_circle = circle_instance;

ref_shape = dynamic_cast<Shape&>(ref_circle);
ref_shape.virtualfunc();
}

但这一次,程序调用了基类的virtualfunc(),结果是:In Shape

如果您让我知道我缺少哪些引用概念以及如何更改 main() 中的引用以获得指针版本中的结果,我将不胜感激。

谢谢

最佳答案

无法重新安装引用。一旦你在初始化中初始化了引用,它就变成了被引用对象的别名,无法与之区分开来。后面的赋值:

ref_shape = dynamic_cast<Shape&>(ref_circle);

真正的意思:

shape_instance = dynamic_cast<Shape&>(ref_circle);

另一方面,您可以将新引用绑定(bind)到对象(并且您不需要 dynamic_cast,因为从引用到派生到对基的引用的转换是隐式的):

Shape & another_ref = ref_circle;
another_ref.virtualfunc(); // Dispatches to Circle::virtualfunc

关于c++ - 如何用 C++ 中的引用替换指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15400891/

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