无法访问类变量

Can't accesses class variables

本文关键字:类变量 访问      更新时间:2023-10-16

你好,我是c++和头文件的新手,我不知道如何获得我在头文件中声明的变量。

MyClass.h

#pragma once
#include <iostream>
class MyClass
{
private:
    int numberOfJellyBeans;
public:
    MyClass();
    ~MyClass();
    void GenerateJellyBeans();
}

MyClass.cpp

#include "MyClass.h"
MyClass::MyClass()
{
    //constructor
}
MyClass::~MyClass()
{
    //destructor
}
void GenerateJellyBeans()
{
    //doesnt work?
    numberOfJellyBeans = 250;
    //Also doesnt work
    MyClass::numberOfJellyBeans = 250;
}

GenerateJellyBeans()必须在MyClass的范围内,因此您必须写:

void MyClass::GenerateJellyBeans()
{
  numberOfJellyBeans = 250;
}

现在c++知道GenerateJellyBeans()MyClass的成员,你现在可以访问你的类的变量了

如果您只是简单地声明void GenerateJellyBeans(),则没有this供编译器使用(实际上numberOfJellyBeans = 250;this->numberOfJellyBeans = 250;的简写)

您意外地定义了一个名为GenerateJellyBeans的与MyClass::GenerateJellyBeans无关的自由函数。修改:

void MyClass::GenerateJellyBeans()
     ^^^^^^^^^

现在可以访问numberOfJellyBeans:

{
    numberOfJellyBeans = 250;
}