无法访问类变量
Can't accesses class variables
你好,我是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;
}
相关文章:
- 如何在C++子类中访问父类的私有变量
- 分段 访问私有类变量时出错
- 从不同C++类的成员变量访问成员函数
- 如何访问基类向量中的子类变量?(对于实体组件系统)
- 如何在构造函数中访问类变量以分配它们,而无需在C++中使用此指针
- 类变量无法从类方法访问
- 从静态成员函数访问私有非静态类变量 - C++
- 无法使用子类变量访问超类公共成员
- 基类无法访问的公共成员变量
- 将指针作为参数分配给类变量,然后使用它抛出读取访问违规
- 如何在类别内的类中访问类中的结构变量
- 嵌套类:如何访问封闭类中的成员变量
- 在类组合中,使包含的类可以访问容器类变量
- 如何使用unique_ptr访问C++中的类成员和类变量
- 访问父类变量
- 派生自非模板基类的模板类:无法访问基类变量
- 子类无法访问父类的变量
- 访问容器类变量的对象 - C++
- 如何在类之间访问变量
- 递归函数中的类变量访问