另一个“类型的引用的无效初始化”是指:错误 [英] Another "invalid initialization of reference of type" error

查看:68
本文介绍了另一个“类型的引用的无效初始化”是指:错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的班级中有这样的容器:

I have container in my class like this:

protected:
std::map<const AAA*, std::set<BBB*> > conn;

以下两种getter函数都可以正常工作:

Both of the following getter functions works just fine:

std::map<const AAA*, std::set<BBB*> > & getConnectors()       {return connectors;}
std::map<const AAA*, std::set<BBB*> >   getConnectors() const {return connectors;}

但&错误:

std::map<const AAA*, std::set<BBB*> > & getConnectors() const {return connectors;} //error

错误为:

/home.../Multi.hpp:65:108: error: invalid initialization of reference of type ‘std::map<const AAA*, std::set<BBB*> >&’ from expression of type ‘const std::map<const AAA*, std::set<BBB*> >’
make[2]: *** [CMakeFiles/SimMobility.dir/main.cpp.o] Error 1

为什么要得到这个,请问如何解决

why I am getting this and How may I solve it please

谢谢

推荐答案

这不起作用,因为使用 const 方法的所有成员(除了可变应视为它们本身是 const

This doesn't work because from a const method all members (besides mutable) should be treated as if they are const themselves.

这意味着不仅不能从该方法修改它们,而且不能用非常量指针指向它们或形成对非常量的引用。

This means that not only you can't modify them from that method, but also you can't point to them with a pointer to non-const or form a reference to non-const.

因此,请使用:

      std::map<Foo, Bar> & GetConnectors();
const std::map<Foo, Bar> & GetConnectors() const;

这篇关于另一个“类型的引用的无效初始化”是指:错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆