是否可以将引用保留为 C++ 中的类成员?请举个例子

发布于 2024-12-11 13:27:05 字数 131 浏览 5 评论 0原文

据我所知,引用需要同时声明和初始化。

我想,它的唯一用途在于传递参数以及在某些情况下的多态性。

是否可以将引用保留为类中的数据成员?

如果是的话,我们什么时候需要它?

请给我一个例子。

As far as I know, References need to be declared and initialized at the same time.

I guess, its only use lies in passing arguments and in some cases Polymorphism.

Is it possible to keep a reference as a data member in a class?

If yes, when should we need that?

Please give me an example.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

岁月流歌 2024-12-18 13:27:05

当引用是类的组成部分时,您可以将引用用作类成员,没有引用,类将无法运行,并且您希望在多个类之间共享此部分或多态性地使用它:

class Presenter
{
    IView & view;
    IModel & model;

    Presenter(IView & view, IModel & model)
        : view(view), model(model)
    {
    }
};

引用成员在构造后无法更改,因此使用一个可以有力地说明该类的用途。使用常规或智能指针可提供更大的灵活性。

You would use a reference as a class member when it is an integral part of the class, without which the class cannot function, and you want to either share this part among several classes or use it polymorphically:

class Presenter
{
    IView & view;
    IModel & model;

    Presenter(IView & view, IModel & model)
        : view(view), model(model)
    {
    }
};

A reference member cannot be changed after construction, so using one makes a strong statement about how the class is meant to be used. Using regular or smart pointers offers more flexibility.

可以拥有引用类型数据成员,但作为一般规则,您不应该声明引用类型数据成员。具有引用类型数据成员的类是不可分配的(因为引用不可分配);这极大地限制了类的使用。

使用指针类型数据成员几乎总是更好,因为它们有效地提供相同的功能,具有相同的生命周期约束,但不会使类不可分配。

You can have reference-type data members, but as a general rule you should not declare reference-type data members. A class with a reference-type data member is not assignable (because references are not assignable); this greatly restricts the use of the class.

It's almost always preferable to use pointer-type data members, since they effectively provide the same capabilities, with the same lifetime constraints, but without making the class not assignable.

╭⌒浅淡时光〆 2024-12-18 13:27:05

正如唐所指出的,引用成员的使用方式与指针成员的使用方式大致相同。我认为值得指出的是,指针也可以为空,也可以重新定位,因此在大多数方面都更有用。

此外,在现代 C++ 中,您可能不会使用指针或引用成员,因为您可以使用 shared_ptrunique_ptr 更好地封装成员的生命周期

As don has pointed out a reference member can be used in much the same way as a pointer member. I think it is worth pointing out though that pointers can also be null and also be reseated so are much more useful in most respects.

additionally, in modern C++ you probably wouldn't use a pointer or reference member as you can use shared_ptr or unique_ptr to better encapsulate the lifetime of the members

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文