2013-04-06 129 views
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

GenerateJellyBeans()必須是在MyClass範圍,所以你必須寫:

void MyClass::GenerateJellyBeans() 
{ 

    numberOfJellyBeans = 250; 
} 

現在C++知道GenerateJellyBeans()MyClass的成員,你現在可以訪問你的類的變量。

如果你只是把它聲明平原void GenerateJellyBeans(),沒有this編譯器一起工作(實際上numberOfJellyBeans = 250;this->numberOfJellyBeans = 250;簡寫)

1

你不小心定義一個名爲GenerateJellyBeans免費功能是無關MyClass::GenerateJellyBeans。要糾正這一點,

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

現在,你就可以訪問numberOfJellyBeans

{ 
    numberOfJellyBeans = 250; 
} 
+0

謝謝你,我才意識到我忘了更新我的頭後,我加入了一些參數時我曾嘗試過這樣做。 – epelc 2013-04-06 18:08:39