如何从指针中提取引用?
请原谅我,因为我的 C++ 很生疏。但我陷入了困境。我正在尝试制作一个自定义列表,其中包含返回最前面和最后面的项目的方法。
ElementType& front() throw(string*)
{
if (empty())
throw new string("Empty Vector");
else
return(first)
}
我的主要问题是我没有实际的第一个项目,我有一个指向它的指针,但我不知道如何仅使用指针来获取指针所指向的内容的引用。我尝试过类似的事情:
ElementType& *first
或者
&*first
但我无法让它们很好地发挥作用。任何建议将不胜感激。
Forgive me as my C++ is very rusty. But I am in a bind. I am trying to make a custom list that have methods to return the front most, and back most items.
ElementType& front() throw(string*)
{
if (empty())
throw new string("Empty Vector");
else
return(first)
}
My main problem is that I don't have the actual first item, I have a pointer to it and I have no idea how to go about taking a reference of what the pointer is pointing it, using only the pointer. I've tried things similar to:
ElementType& *first
or
&*first
but I can't get them to play nicely. Any advice would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果
first
是指向元素的指针,则*first
将为您提供对其的引用。If
first
is a pointer to your element,*first
will give you a reference to it.我认为,将变量
first
声明为一个指向ElementType
对象引用的指针。我不确定这是否是有效的 C++。如果返回此值,则返回指针
first
指向的取消引用对象的地址,我认为这相当于返回first
。如果
first
是指向第一个 ElementType 项的指针,则只需将取消引用的对象返回为*first
即可。顺便说一句,这并不是您的代码中唯一看起来错误的地方。我不认为抛出字符串指针是一个好的做法(抛出一个从
std::exception
派生的对象,例如std::out_of_range
),也不包括异常规范(这会产生不必要的开销)。所以你可能会追求类似这样的东西:Declares a variable
first
to be, I think, a pointer to a reference to anElementType
object. I'm not sure that is even valid C++.If you return this, you are returning the address of the dereferenced object pointed to by pointer
first
, which I believe amounts to just returningfirst
.If
first
is a pointer to the first ElementType item, just return the dereferenced object as*first
.By the way, that's not the only thing that looks wrong with your code. I don't think throwing string pointers is good practice (throw an object derived from
std::exception
, such asstd::out_of_range
), nor is including the exception specification (it incurs unnecessary overhead). So you're probably after something more like this:ElementType& *first
不合法。你不能有一个指向引用的指针。
只需取消引用指针,您就可以引用它。
例如,假设
first
是一个指针:ElementType& *first
Is not legal. You can't have a pointer to a reference.
Just derefence the pointer and you will have a reference to it.
Example, assuming
first
is a pointer: