2013-08-16 193 views
1

我有這個類無法訪問公共靜態方法

#pragma once 
namespace CMT{ 
namespace sql=System::Data::SqlClient; 
public ref class db 
{ 
public:db(void){} 
public: static sql::SqlConnection SC(){ 
      System::String cstring="data source=192.168.0.139\\cedfit; "+ 
       "initial catalog=cedfitdb; user id=client; password=cedfit"; 
      sql::SqlConnection sc=new sql::SqlConnection(cstring); 
      return sc; 
     } 

}; 
} 

現在,當我去我的表格1加載事件,我不能訪問我的分貝的SC()方法,爲什麼?

我也試圖讓在Form1 Load事件的代碼:

System::Data::SqlConnection mycon=db::SC(); 
mycon.Open();//I also tried mycon->Open() and mycon::Open() 

爲什麼它不工作?爲什麼程序不能識別「Open()」? 另外,當我把#include "db.h"上CMT.cpp它說cannot covert from System::Data::Sqlclient::SqlConnection to int 我相信我正在返回一個SqlConnection,但爲什麼?

+0

莫非你請正確縮進代碼並更新問題? –

+0

是否可以上傳整個解決方案? – user1625766

+0

@ user1625766沒有必要。但是你應該澄清你使用的C++的方言。它看起來像C++/CLI,但也可以是C++/CX。 – PeterT

回答

3

嘗試在.NET框架中通過C++/CLI使用引用類型時出現很多錯誤。

- 在引用C++/CLI中的.NET引用類型時,您需要使用^。此外,在爲參考類型分配內存時,您需要使用gcnew而不是new。請參見下面的變化:

static sql::SqlConnection^ SC() 
{ 
    System::String^ cstring = "data source=" + "asdfasdf"; 
    sql::SqlConnection^ sc = gcnew sql::SqlConnection(cstring); 

    return sc; 
} 

- 試圖用該方法在你的代碼時,這是再次的問題。此外,您沒有爲SqlConnection以及CMT::db::SC指定正確的名稱空間。

int main(array<System::String ^> ^args) 
{ 
    System::Data::SqlClient::SqlConnection^ mycon = CMT::db::SC(); 
    mycon->Open(); 

    return 0; 
} 

作爲一個側面說明,有沒有你需要的C++/CLI而不是C#一個特別的原因?當然有些情況下C++/CLI是有益的,但如果你不試圖與本地代碼進行交互,它也可能是不必要的複雜。只是一個想法。

全碼:

db.h

#pragma once 

namespace CMT { 
namespace sql = System::Data::SqlClient; 

ref class db 
{ 
public: 

    db(void) 
    { 
    } 

    static sql::SqlConnection^ SC() 
    { 
     System::String^ cstring = "whatever"; 
     sql::SqlConnection^ sc = gcnew sql::SqlConnection(cstring); 

     return sc; 
    } 

}; 

} 

Main.cpp的

// ConsoleApplication1.cpp : main project file. 

#include "stdafx.h" 
#include "db.h" 

using namespace System; 

int main(array<System::String ^> ^args) 
{ 
    System::Data::SqlClient::SqlConnection^ mycon = CMT::db::SC(); 
    mycon->Open(); 

    return 0; 
} 
+0

1> c:\ users \ sherwin \ desktop \ cmt \ cmt \ Form1.h(73):error C2039:'SC':不是'CMT'的成員 1> c:\ users \ sherwin \ desktop \ cmt \ cmt \ Form1.h(73):錯誤C3861:'SC':標識符未找到 1>生成日誌保存在「file:// c:\ Users \ SHERWIN \ Desktop \ CMT \ CMT \ Debug \ BuildLog .htm「 1> CMT - 3個錯誤,0個警告 ==========構建:0成功,1失敗,0最新,0跳過=== ======= – user1625766

+0

@ user1625766你是否包含相應的* .h文件? – PeterT

+0

是我把#include「db.h」放在CMT.cpp – user1625766