2013-06-05 46 views
2

的main.cpp無法從一個類訪問另一個類的實例

#include "stdafx.h" 
#include <iostream> 
#include "Form1.h" 
#include "myclass.h" 
using namespace Akva; 

[STAThreadAttribute] 
int main(array<System::String ^> ^args) 
{ 

Application::EnableVisualStyles(); 
Application::SetCompatibleTextRenderingDefault(false); 
Form1^ MainForm = gcnew Form1(); 
Application::Run(MainForm); 
return 0; 
}; 

Form1.h

#include "myclass.h" 
public ref class Form1 : public System::Windows::Forms::Form 
{ 
     ... 
    }; 

myclass.h

#include "Form1.h" 
class MyClass 
{ 
    public: void addBox(); 
}; 

void MyClass::addBox() 
{ 
    PaintBox^ pb = cgnew PaintBox(); 
    MainForm->Controls->Add(pb); //here 
}; 

I無法從「MyClass」類訪問main.cpp中的實例「MainForm」。 我怎麼能得到它?

UPD:myclass.h中的代碼包含在創建實例MainForm之前,並且Form1的實例在myclass.h中不可見。

#include "stdafx.h" 
#include <iostream> 
#include "Form1.h" 
#include "myclass.h" 
using namespace Akva; 

[STAThreadAttribute] 
int main(array<System::String ^> ^args) 
{ 

Application::EnableVisualStyles(); 
Application::SetCompatibleTextRenderingDefault(false); 
Application::Run(gcnew Form1()); //here 
return 0; 
}; 

另一個問題:我如何訪問Form1的元素和實例?

我想從「MyClass」創建PictureBox。

+0

您的myclass。h頭文件#包含Form1.h。您的Form1.h頭文件#includes myclass.h。像這樣的循環依賴不能工作。你將不得不重構你的代碼,所以這不會發生。其中通常涉及將某些方法的實現從Form1.h移動到.cpp文件中。 –

回答

0

我無法從類「MyClass」訪問main.cpp中的實例「MainForm」。我怎麼能得到它?

MainForm是方法main內的局部變量。該方法之外的代碼將永遠無法讀取該局部變量。

您可以將包含在MainForm局部變量中的實例傳遞給其他代碼,以便其他代碼可以訪問它,但沒有足夠的代碼顯示可以幫助您做到這一點。

您嘗試訪問的方式MainFormMyClass::addBox就像是一個全局變量。那是你想要做什麼?全局變量通常是要避免的,但如果這是你想要的,可以在一個頭文件中聲明它,main.cppmyclass.cpp都可以看到,並且像在main()中那樣進行初始化。

1

我怎麼能得到它?

您需要在main.cpp中使用#include myclass.h才能在Form1之內使用它。

+0

我做到了,但它不起作用。 – warchantua

0

您至少有兩種解決方案:

  • 形式實例傳遞給MyClass的構造

    #include "Form1.h" 
    
    class MyClass 
    { 
        private: MainForm^ mainForm; 
        public: MyClass(MainForm^ mainForm); 
        public: void addBox(); 
    }; 
    
    void MyClass::MyClass(MainForm^ mainForm) 
    { 
        this->mainForm = mainForm; 
    } 
    
    void MyClass::addBox() 
    { 
        PaintBox^ pb = cgnew PaintBox(); 
        mainForm->Controls->Add(pb); //here 
    }; 
    
  • 傳遞形式實例的addBox方法:

    #include "Form1.h" 
    
    class MyClass 
    { 
        public: void addBox(MainForm^ mainForm); 
    }; 
    
    void MyClass::MyClass(MainForm^ mainForm) 
    { 
        this->mainForm = mainForm; 
    } 
    
    void MyClass::addBox(MainForm^ mainForm) 
    { 
        PaintBox^ pb = cgnew PaintBox(); 
        mainForm->Controls->Add(pb); //here 
    }; 
    
相關問題