c++ - 这是什么意思:“成员引用类型'Human *'是一个指针;你的意思是使用'->'吗?”
问题描述
我正在研究 C++ 中的类。
我基本上是在改造我在这里所做的事情,但是在 C++ 中。
它进展顺利,但我不明白错误的member reference type 'Human *' is a pointer; did you mean to use '->'?
含义。我从未使用过->
,也曾见过*
以这种方式使用(如const char *
),但我不太确定它是如何工作的。
我发现的最接近的问题是这个,但答复没有帮助。
这是我的代码
#include <stdio.h>
#include <cstdlib>
#include <iostream>
using std::cout;
using std::cin;
using std::string;
class Human {
public:
string Name;
int Age;
double Height;
void Initialise(string name, int age, double height) {
this.Name = name; // Error here
this.Age = age; // Error here
this.Height = height; // Error here
}
void Grow(double rate) {
if (rate < 0) {
cout << "You can't grow at a negative rate, silly.\n";
return;
}
else if (rate >= 0.2) {
cout << "You can't grow that high, silly.\n";
return;
}
this.Height += rate; // Here too
}
};
int main() {
return 0;
}
解决方案
this
总是一个指针,所以你不能说this.Name
——你需要说(*this).Name
。语法
a->b
相当于(*a).b
你可以说this->Name
(这是错误消息明确建议的内容),尽管:里面的方法,
this->
是多余的。通常您可以简单地引用或分配给,Name
(尽管正如 Jeremy Friesner 在他的评论中指出的那样,可能存在您可能真正想要或需要它的罕见/深奥的情况)。正如评论所说,必须正式学习 C++。您只需要知道第 1 点和第 2 点(以及一百万其他类似的约定)。你不能偶然发现它们。试错是行不通的。
->
语法甚至不是 C++ 特定的。它是 C 的一部分。C 规则手册非常精简——所以在继续讨论(这里我只能同意 user4581301)C++ 的“batsmurf crazy”复杂性之前,最好先正式学习这一点。
推荐阅读
- constraints - 这个线性规划问题的约束是什么?
- python - 问题将 2 个输入拟合到我的 keras 模型
- css - 为什么我没有在 React Native 中获得神经拟态设计?
- c# - ADOMD.NET 中的连接 - 轮询连接状态
- webpack - Webpack - 图像未正确加载
- oracle - oracle如何从嵌套表中删除NULL元素
- php - 我的 API 未收到从 Trading View Widget 发送的 PHP POST
- email - 无法从 Unifi 控制器向 Postfix SMTP 中继发送电子邮件通知
- r - 根据每个组 id 的条件创建新变量
- scala - Spark 不推送过滤器/分区,即 PushedFilters 和 PartitionFilter 为空)