0

こんにちは、私は 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;
}
4

2 に答える 2

4

GenerateJellyBeans()のスコープ内にMyClassある必要があるため、次のように記述する必要があります。

void MyClass::GenerateJellyBeans()
{

  numberOfJellyBeans = 250;
}

これで、 C++GenerateJellyBeans()は が のメンバーであることを認識しMyClass、クラスの変数にアクセスできるようになりました。

plain と宣言するだけでは、コンパイラが使用できるvoid GenerateJellyBeans()ものはありません(実際には の省略形です) 。thisnumberOfJellyBeans = 250;this->numberOfJellyBeans = 250;

于 2013-04-06T18:06:33.317 に答える
1

GenerateJellyBeansとは関係のない自由な関数を誤って定義していMyClass::GenerateJellyBeansます。これを修正するには:

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

これで、次の場所にアクセスできるようになりますnumberOfJellyBeans:

{
    numberOfJellyBeans = 250;
}
于 2013-04-06T18:05:54.473 に答える