如何在使用对象指针时访问成员函数

How to access member functions when using object pointers

本文关键字:访问 成员 函数 指针 对象      更新时间:2023-10-16

我正试图通过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 <<
"ttMemory Address: " << &nPtr1 << endl <<
"ttPoints to: " << nPtr1 << endl <<
"ttValue of Pointee: " << nPtr1->GetValue() << endl <<
endl <<
"tnPtr2: " << endl <<
"ttMemory Address: " << &nPtr2 << endl <<
"ttPoints to: " << nPtr2 << endl <<
"ttValue 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

然而,Value of Pointee的预期输出应该反映节点初始化时使用的布尔值。


我尝试过使用*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)