繁体   English   中英

即使您没有将结构显式定义为指针,为什么还要使用 -> 来访问结构成员变量?

[英]Why do you use -> to access struct member variables even if you haven't explicitly defined the struct as a pointer?

我有一个从未明确定义为指针的结构。 但是当我尝试使用. 而不是-> ,我得到一个错误, ->似乎是唯一正确的选择。

据我了解,您只能使用->取消引用指向 class 的指针并访问其成员。 在下面的代码中, Employee不是指针,但如果我使用. ,我得到一个错误。 为什么呢?

struct Employee {
  public:
    int getAge(){ return this.age; }
    void setAge(int age){ this.age = age; }
  private:
    int age{18};
};

int main() {
  Employee emp;
  emp.setAge(55);
  std::cout << emp.getAge() << '\n';
}

在 C++ 中, this是指向当前 object 的指针,而不是对其的引用。 因此,即使您从未声明过任何指针,但如果您使用this ,您将需要使用指针语法。

this是指针而不是引用的原因是历史性的。 this关键字是在引用之前添加到语言中的。)

您必须使用->运算符的原因是因为this是一个指针。 它是一种特殊的指针。 this指针是指向 object 的指针,其中成员 function 被调用。 This用于检索 object。 您示例中的this指针正在检索 object age this指针也是一个 r 值。 特别是prvalue 这里也是参考 感谢@user4581301 也为此做出了贡献。

例如使用您的示例并调整一些内容:

#include <iostream>

struct Employee {
public:
 // You want to use pointer syntax for the this pointer. By using the arrow operator.
    int getAge() { return this->age; }
    void setAge(int age) { this->age = age; } //Then changing setAge to an int rather than a string.
private:
    int age{ 18 };
}; // Don't forget the semicolon. 

int main() {
    Employee emp;
    emp.setAge(55);
    std::cout << emp.getAge() << '\n';
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM