c++ - 使用对象指针时如何访问成员函数

标签 c++ 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

但是 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/

相关文章:

c++ - 为什么我得到一个 "' 初始化' : cannot convert from 'initializer list' to '_Objty' "error in C++?

c++ - QTableWidget 随机加载效率低下 - C++

c - 时间不正确,但代码似乎正确 :S (unexpected outcome)

c - void * 赋值问题

c++ - 指向数组的指针,然后获取完整的数组 C++

c++ - cv::createLineSegmentDetector() 函数的 Opencv4nodejs 插件崩溃。异常只能被 catch(...) 捕获。如何调试异常类型?

c++ - 如何在多个单元测试中使用用户输入变量?

c++ - g++ 编译器 : optimization flag adds warning message

c++ - 为我的对象分配特定/明确的内存位置

c - 在文件的字符数组中搜索 2 个连续的十六进制值