我试图通过 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
但是 Value of Pointee
的预期输出应该反射(reflect)节点初始化时使用的 bool 值。
我尝试过使用 *nPtr2->GetValue()
和 *nPtr2.GetValue()
,但这两种方法都会导致语法错误。
通过指针访问这些成员函数的正确方法是什么?如果我正确访问它们,那么为什么节点的值与预期不匹配?
最佳答案
Node *nPtr1 = &n1;
Node *nPtr2 = nPtr1;
当然,您在记录 m_value
字段时会得到相同的结果。 :) 您甚至可以在日志中看到它们都指向同一个实例。
关于c++ - 使用对象指针时如何访问成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58602282/