如何在使用对象指针时访问成员函数
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 <<
"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)
相关文章:
- C++ 传递指向对象的指针的指针,无法访问成员
- 从不同C++类的成员变量访问成员函数
- 使用 getter 访问成员变量C++
- 如何使用包含内部类的类实例有效地从内部类访问成员?
- 通过多个类访问成员时出错
- 如何在使用对象指针时访问成员函数
- 为什么相应成员不能正确访问成员函数指针
- 从两个不同类继承的非虚拟基类的访问成员
- 如何使用 gcc 内联汇编器代码访问成员变量
- 如何使用常数向量访问成员函数
- 访问成员函数中参数的类成员
- C++嵌套结构初始化和访问成员
- 通过指向班级第一个成员的指针访问成员是不确定的行为吗?
- 如何使用C STD :: SET中的迭代器访问成员功能
- 访问成员C 时,结构的向量生成了范围的错误
- 带指针的班级访问成员
- 从聚合类访问成员变量
- 如何访问成员变量 sqlite 回调
- ctypes/C++segfault访问成员变量
- 通过父类型的指针或直接从派生类访问成员函数的差异