首页 > 解决方案 > 这是什么意思:“成员引用类型'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;
}

标签: c++pointers

解决方案


  1. this总是一个指针,所以你不能说this.Name——你需要说(*this).Name

  2. 语法a->b 相当于(*a).b可以this->Name(这是错误消息明确建议的内容),尽管:

  3. 里面的方法,this->是多余的。通常您可以简单地引用或分配给,Name (尽管正如 Jeremy Friesner 在他的评论中指出的那样,可能存在您可能真正想要或需要它的罕见/深奥的情况)。

  4. 正如评论所说,必须正式学习 C++。您只需要知道第 1 点和第 2 点(以及一百万其他类似的约定)。你不能偶然发现它们。试错是行不通的。

  5. ->语法甚至不是 C++ 特定的。它是 C 的一部分。C 规则手册非常精简——所以在继续讨论(这里我只能同意 user4581301)C++ 的“batsmurf crazy”复杂性之前,最好先正式学习这一点。


推荐阅读