[英]c++ - call member function on dereferenced object pointer
template <typename T>
class Node {
private:
T data;
Node<T> * next;
public:
Node(T _data, Node<T> * _next): data(_data), next(_next){}
T get_data() const {
return this->data;
}
Node<T> * get_next() const {
return this->next;
}
void set_data(T data) {
this->data = data;
}
void set_next(Node<T> * next) {
this->next = next;
}
};
now I try to invoke the 'set_next()' function on the dereferenced object pointer:现在我尝试在取消引用的对象指针上调用“set_next()”函数:
Node<T> new_element(element, NULL);
Node<T> * tmp = this->get_last(); // returns a pointer to the last element
*tmp.set_next(&new_element);
when I try to compile the console prints this errer message:当我尝试编译控制台时会打印此错误消息:
error: request for member ‘set_next’ in ‘tmp’, which is of pointer
type ‘Node<int>*’ (maybe you meant to use ‘->’ ?)
*tmp.set_next(&new_element);
I don't understand why the compiler wants me to use '->' because '.'我不明白为什么编译器要我使用 '->' 因为 '.' is a perfectly fine way to invoke a public member function, right?是调用公共成员函数的完美方法,对吗?
However when I put:然而,当我把:
Node<T> new_element(element, NULL);
Node<T> * tmp = this->get_last();
*tmp->set_next(&new_element);
I get this:我明白了:
error: void value not ignored as it ought to be
*tmp->set_next(&new_element);
I don't understand what that means, can someone help me?我不明白这是什么意思,有人可以帮助我吗?
Due to operator precedence,由于运算符优先,
*tmp.set_next(&new_element);
is the same as是相同的
*(tmp.set_next(&new_element));
which is clearly not what you want.这显然不是你想要的。
You may use您可以使用
(*tmp).set_next(&new_element);
or或者
tmp->set_next(&new_element);
tmp->set_next(&new_element);
is the correct usage.是正确的用法。
The error message occurs because the *
tries to dereference the return value, which is void
.出现错误消息是因为*
尝试取消引用返回值,即void
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.