2017-03-05 69 views
-3

我是UWP和C++的新手。 我正在嘗試編寫一個處理http-api的簡單應用程序。 我的例子:^Uri GetAsync

void ForecastFromMSW::MainPage::GetTheCity(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) 
{ 
    String ^mystr = "http://google.com"; // creating a string object 
    Uri url(mystr); // crating an url object 
    HttpClient cli; //creating an object of HttpClient 
    cli.GetAsync(url); // pass url object to cli 
} 

從編譯器的消息:

1>------ Build started: Project: ForecastFromMSW, Configuration: Debug Win32 ------ 
1> MainPage.xaml.cpp 
1>c:\users\9maf4you\documents\visual studio 2015\projects\forecastfrommsw\forecastfrommsw\mainpage.xaml.cpp(38): error C2664: 'Windows::Foundation::IAsyncOperationWithProgress<Windows::Web::Http::HttpResponseMessage ^,Windows::Web::Http::HttpProgress> ^Windows::Web::Http::HttpClient::GetAsync(Windows::Foundation::Uri ^,Windows::Web::Http::HttpCompletionOption)': cannot convert argument 1 from 'Windows::Foundation::Uri' to 'Windows::Foundation::Uri ^' 
1> c:\users\9maf4you\documents\visual studio 2015\projects\forecastfrommsw\forecastfrommsw\mainpage.xaml.cpp(38): note: No user-defined-conversion operator available, or 
1> c:\users\9maf4you\documents\visual studio 2015\projects\forecastfrommsw\forecastfrommsw\mainpage.xaml.cpp(38): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called 
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== 
========== Deploy: 0 succeeded, 0 failed, 0 skipped ========== 

我看到,編譯器不能一種類型轉換爲另一種,我知道我必須要通過^ URI來GetAsync。但我不知道該怎麼辦。 Thnx。

+1

我不是在C++方面的專家 - CLI,但會不會是簡單地提供像'烏里^ URL(myStr的)聲明;'將解決這一問題? –

回答

-1

編譯器告訴你這個問題

無法從 '視窗:基金會::烏里' 到 '視窗:基金會::烏里^'

解決方法是轉換參數1使用%,cli.GetAsync(%url);的託管「運營商地址」。你可以看到這個同樣的問題,用非常簡單的測試程序:

ref class Foo sealed {}; 
void f(Foo^) {} 

int main(array<System::String ^> ^args) 
{ 
    Foo foo; 
    f(%foo); 
    return 0; 
} 

注意,因爲你調用一個方法*Async(),你可能要認真考慮使用C#。

+0

問題是關於C++/CX,而不是C++/CLI。你的答案不適用。 – IInspectable

3

在C++/CX,對象是使用ref new通常實例化,返回一個REF-計數對象的句柄。修復您的代碼最簡單的方法是用

Uri^ url = ref new Uri(mystr); 

編譯器,以取代

Uri url(mystr); 

將生成代碼,以減小對url裁判計數,當它超出範圍。當引用計數達到零時,該對象會自動銷燬。