没有已知的从指针到指针的引用转换 [英] No known conversion from pointer to reference to pointer

查看:132
本文介绍了没有已知的从指针到指针的引用转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下g ++错误

  Menu.hpp:66:41:错误:到'Menu :: Stack< Submenu *> :: push(Submenu *)'
Menu.hpp:66:41:note:candidate is:
Menu.hpp:14:21: void Menu :: Stack< T> :: push(T&)[with T = Submenu *]
Menu.hpp:14:21:注意:没有已知的参数1从'Submenu *'到'Submenu *&'

如何进行这样的转换是不可能的?编译器在什么样的情况下会出现这样的错误?



至于我实际上在做什么:




  • 我有一个类子菜单

  • 我有一个类继承自Submenu的菜单

  • 菜单有额外的字段类型 Stack< Submenu *> 其中记录打开子菜单的映射

  • 菜单的所有方法如打开菜单指的是当前在堆栈顶部()的子菜单。

  • Menu具有关闭当前子菜单并向上移动的公共方法 - 即从堆栈中弹出子菜单。




现在是最多的部分可能的问题,即菜单的构造函数:

  Menu(){stack.push((Submenu *)this); } 

这样做是因为当所有菜单都关闭时,stack.top



编辑:



我做了我自己的类Stack,而不是使用std :: stack(如我最初建议的),正如答案中所指出的,说谎的问题。对于这种不准确性,请原谅。

解决方案

通常,你只能将lvalues转换为引用,而不是rvalues 。你可以将rvalues转换为 const 引用,这可能是你真正想要的 - 如果你改变 Stack :: push 取一个 const T& 参数,而不是 T& ,错误会消失。 p>

I've got the following g++ error

Menu.hpp:66:41: error: no matching function for call to ‘Menu::Stack<Submenu*>::push(Submenu*)’
Menu.hpp:66:41: note: candidate is:
Menu.hpp:14:21: note: void Menu::Stack<T>::push(T&) [with T = Submenu*]
Menu.hpp:14:21: note:   no known conversion for argument 1 from ‘Submenu*’ to ‘Submenu*&’

How can such a conversion be impossible? On what sort of occasions does compiler issue such errors?

As to what I was actually doing:

  • I have a class Submenu
  • I have a class Menu which inherits from Submenu
  • Menu has additional field of type Stack<Submenu*> which maps remembering open submenus
  • All methods of Menu like "open menu", "click menu item" and so on refer to the Submenu that is currently on top() of the stack. Within class Submenu, they operate on the object itself.
  • Menu has a public method of closing the current submenu and going up - i.e. popping the submenu from the stack.
  • Menu can pop until it reaches itself, see below what does it mean.

Now is the part that is most probably the issue, namely, the constructor of Menu:

Menu() { stack.push( (Submenu*)this ); }

It does so because when all menus get closed, methods relative to stack.top() should refer to the Menu itself, being a kind of Submenu too (since it inherits from it).

EDIT:

I've made my own class Stack instead of using std::stack (as I initially suggested) and, as pointed out in the answer, there lied the problem. Excuse me for that inaccuracy.

解决方案

Generally, you can only convert lvalues to references, not rvalues (a cast is an rvalue). You can convert rvalues to const references, which is probably what you really want here -- if you change Stack::push to take a const T & argument instead of a T &, the errors will go away.

这篇关于没有已知的从指针到指针的引用转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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