[英]How to access member functions when using object pointers
我正在尝试通过nodePtr
访问值Node
,但是遇到了麻烦。
//main//
Node n1 (true);
Node n2 (false);
Node *nPtr1 = &n1;
Node *nPtr2 = nPtr1;
cout << "Memory Locations: " << endl <<
"\tn1: " << &n1 << endl <<
"\tn2: " << &n2 << endl;
cout << "Pointer Info: " << endl <<
"\tnPtr1: " << endl <<
"\t\tMemory Address: " << &nPtr1 << endl <<
"\t\tPoints to: " << nPtr1 << endl <<
"\t\tValue of Pointee: " << nPtr1->GetValue() << endl <<
endl <<
"\tnPtr2: " << endl <<
"\t\tMemory Address: " << &nPtr2 << endl <<
"\t\tPoints to: " << nPtr2 << endl <<
"\t\tValue of Pointee: " << nPtr2->GetValue() << endl <<
endl;
//Node.cpp//
Node::Node(){
m_next = nullptr;
}
Node::Node(bool value){
m_value = value;
m_next = nullptr;
}
void Node::ReplaceValue(){
m_value = !m_value;
}
void Node::SetNext(Node* next){
m_next = next;
}
Node* Node::GetNext(){
return m_next;
}
bool Node::GetValue(){
return m_value;
}
Node::~Node(){
}
当我运行这段代码时,我得到了这个:
Memory Locations:
n1: 0x7ffd33aee010
n2: 0x7ffd33aee000
Pointer Info:
nPtr1:
Memory Address: 0x7ffd33aedfe8
Points to: 0x7ffd33aee010
Value of Pointee: 1
nPtr2:
Memory Address: 0x7ffd33aedfe0
Points to: 0x7ffd33aee010
Value of Pointee: 1
但是,Pointee 的Value of Pointee
应该反映节点初始化的 boolean。
我曾尝试使用*nPtr2->GetValue()
和*nPtr2.GetValue()
,但这两种方法都会导致语法错误。
通过指针访问这些成员函数的正确方法是什么? 如果我正确访问它们,那么为什么节点的值与预期不匹配?
Node *nPtr1 = &n1;
Node *nPtr2 = nPtr1;
当然,在记录m_value
字段时,您会得到相同的结果。 :) 你甚至可以在你的日志中看到它们都指向同一个实例。
nPtr1 和 nPtr2 都指的是同一个实例。
nPtr2 = nPtr1;
nPtr1 指向 n1,所以 nPtr2 现在也指向 n1。 这就是您获得相同价值的原因。
至于以正确的方式访问成员函数。
nPtr2->GetValue();
以上是访问成员函数的正确方法。
*nPtr2->GetValue()
*nPtr2.GetValue()
两者都是错误的。 要了解原因,您需要查看运算符优先级。
第一种方式,即*nPtr2->GetValue(),'->'操作符的优先级更高,所以类似这样
*(nPtr2->GetValue())
这意味着您正在尝试取消引用 (*) GetValue() 的返回值,它是一个布尔值。
在第二种方式中,即 *nPtr2.GetValue(),'.' 运算符具有更高的优先级,所以类似于写
*(nPtr2.GetValue())
由于 nPtr2 是一个指针,你不能使用 '.' 在上面。
您可以在此处阅读有关运算符优先级的更多信息( https://en.cppreference.com/w/cpp/language/operator_precedence )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.