2011-07-14 18 views
3

我在使用C++/CLI命名空間創建託管類時遇到了問題。在C++/CLI中創建託管類和名稱空間的問題

我想做到以下幾點:

#pragma once 
#include "abc.h" 
#ifdef _MANAGED 
#using <system.dll> 
using namespace System; 
using namespace System::IO; 
using namespace System::Collections::Generic; 
using namespace System::Globalization; 
#endif 

namespace Animals 
    { 
    public ref class Pets 
     { 
     Pets::Pets(){} 
     }; 
    } 

我有幾個不同的問題:

A)當我這樣的代碼放到.cpp文件,它編譯罰款。但是,它看起來名稱空間不能按預期工作(請參閱我創建的這個問題:Namespace not recognized in C++/CLI)列出的唯一答案是我必須在頭文件中聲明類/名稱空間。但這是一個問題,因爲..

B)編譯器在將它放置在頭文件中時抱怨public ref class Pets。它說,必須有一個語法錯誤。

智能感知錯誤:

expected a declaration

其他錯誤:

'{' : missing function header (old-style formal list?)

syntax error: 'public'

我似乎無法找到任何偉大的C++/CLI的例子,顯示這兩個頭文件和cpp文件。

所以我的問題是:如何使託管類和命名空間都按預期工作? (即我做錯了什麼?)

請讓我知道,如果我需要包括任何更多的信息。

預先感謝您的時間和耐心:)

+0

請給你的頭文件。它可能只包含前向聲明。 – marc

+0

@marc:我剛剛將上面的代碼移入和移出標題。 (沒有額外的代碼用來顯示你)。 – developer

+0

你得到了什麼確切的錯誤? – marc

回答

3

在頭文件應該只是向前聲明。

// abc.h 
#pragma once 

namespace Animals 
{ 
    public ref class Pets 
    { 
     Pets(); // forward declaration 
     // Pets::Pets is redundant and wrong, because you are inside 
     // the class Pets 
    }; 
} 


// abc.cpp 
#include "abc.h" 
#ifdef _MANAGED 
#using <system.dll> 
using namespace System; 
using namespace System::IO; 
using namespace System::Collections::Generic; 
using namespace System::Globalization; 
#endif 

namespace Animals 
{ 
    Pets::Pets() {} // implementation 
    // Now Pets::Pets() is right, because you dont write the class... wrapper again. 
} 
相關問題