Что вызывает неоднозначные ошибки символов? С++

Я пытаюсь изучить С++, создавая небольшое приложение для Windows Phone. В настоящее время я просто следую учебнику, чтобы разобраться с разработкой для Windows Phone. Однако я столкнулся с неоднозначной ошибкой сигнала при попытке построить код. Я привык к тонкостям, связанным с Java, и немного не понимаю, что может быть причиной этой ошибки. Дамп ошибки, который я получаю:

1>c:\program files (x86)\windows phone kits\8.0\include\wrl\event.h(740): error C2872:        'EventRegistrationToken' : ambiguous symbol
1>          could be 'c:\program files (x86)\windows phone kits\8.0\include\eventtoken.h(51) : EventRegistrationToken'
1>          or       'c:\program files (x86)\windows phone kits\8.0\windows metadata\windows.winmd : Windows::Foundation::EventRegistrationToken'
1>          c:\program files (x86)\windows phone kits\8.0\include\wrl\event.h(1035) : see reference to class template instantiation 'Microsoft::WRL::EventSource<TDelegateInterface>' being compiled
1>c:\program files (x86)\windows phone kits\8.0\include\wrl\event.h(814): error C2872: 'EventRegistrationToken' : ambiguous symbol
1>          could be 'c:\program files (x86)\windows phone kits\8.0\include\eventtoken.h(51) : EventRegistrationToken'
1>          or       'c:\program files (x86)\windows phone kits\8.0\windows metadata\windows.winmd : Windows::Foundation::EventRegistrationToken'

Код прикреплен ниже - извините, что дал весь файл, но я буквально не знаю, с чего начать. Любая помощь будет принята с благодарностью.

Спасибо

#include "pch.h"
#include "WindowsPhoneGame.h"
#include "BasicTimer.h"
//#include <string.h>
#include <sstream>

//using namespace std;
using namespace Windows::ApplicationModel;
using namespace Windows::ApplicationModel::Core;
using namespace Windows::ApplicationModel::Activation;
using namespace Windows::UI::Core;
using namespace Windows::System;
using namespace Windows::Foundation;
using namespace Windows::Graphics::Display;
using namespace concurrency;


WindowsPhoneGame::WindowsPhoneGame() :
m_windowClosed(false),
m_windowVisible(true)
{
}

void WindowsPhoneGame::Initialize(CoreApplicationView^ applicationView)
{
applicationView->Activated +=
    ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this,   &WindowsPhoneGame::OnActivated);

CoreApplication::Suspending +=
    ref new EventHandler<SuspendingEventArgs^>(this, &WindowsPhoneGame::OnSuspending);

CoreApplication::Resuming +=
    ref new EventHandler<Platform::Object^>(this, &WindowsPhoneGame::OnResuming);

m_renderer = ref new Renderer();
}

void WindowsPhoneGame::SetWindow(CoreWindow^ window)
{
window->VisibilityChanged +=
    ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this,  &WindowsPhoneGame::OnVisibilityChanged);

window->Closed += 
    ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this,  &WindowsPhoneGame::OnWindowClosed);

window->PointerPressed +=
    ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &WindowsPhoneGame::OnPointerPressed);

window->PointerMoved +=
    ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &WindowsPhoneGame::OnPointerMoved);

window->PointerReleased +=
    ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &WindowsPhoneGame::OnPointerReleased);

m_renderer->Initialize(CoreWindow::GetForCurrentThread());
}

void WindowsPhoneGame::Load(Platform::String^ entryPoint)
{
}

void WindowsPhoneGame::Run()
{
BasicTimer^ timer = ref new BasicTimer();

while (!m_windowClosed)
{
    if (m_windowVisible)
    {
        timer->Update();
        CoreWindow::GetForCurrentThread()->Dispatcher- >ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
        m_renderer->Update(timer->Total, timer->Delta);
        m_renderer->Render();
        m_renderer->Present(); // This call is synchronized to the display frame rate.
    }
    else
    {
        CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
    }
}
}

void WindowsPhoneGame::Uninitialize()
{
}

void WindowsPhoneGame::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
{
m_windowVisible = args->Visible;
}

void WindowsPhoneGame::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
{ 
m_windowClosed = true;
}

void WindowsPhoneGame::OnPointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
{
ostringstream sstream;
sstream << "Pressed at: " << "X: " << args->CurrentPoint->Position.X << " Y: " << args->CurrentPoint->Position.Y << "\n";
string s = sstream.str();
OutputDebugStringA(s.c_str());
}

void WindowsPhoneGame::OnPointerMoved(CoreWindow^ sender, PointerEventArgs^ args)
{
ostringstream sstream;
sstream << "Moved at: " << "X: " << args->CurrentPoint->Position.X << " Y: " <<  args->CurrentPoint->Position.Y << "\n";
string s = sstream.str();
OutputDebugStringA(s.c_str());
}

void WindowsPhoneGame::OnPointerReleased(CoreWindow^ sender, PointerEventArgs^ args)
{
    ostringstream sstream;
sstream << "Released at: " << "X: " << args->CurrentPoint->Position.X << " Y: " << args->CurrentPoint->Position.Y << "\n";
string s = sstream.str();
OutputDebugStringA(s.c_str());
}

void WindowsPhoneGame::OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args)
{
CoreWindow::GetForCurrentThread()->Activate();
}

void WindowsPhoneGame::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args)
{
// Save app state asynchronously after requesting a deferral. Holding a deferral
// indicates that the application is busy performing suspending operations. Be
// aware that a deferral may not be held indefinitely. After about five seconds,
// the app will be forced to exit.
SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();
m_renderer->ReleaseResourcesForSuspending();

create_task([this, deferral]()
{
    // Insert your code here.

    deferral->Complete();
});
}

void WindowsPhoneGame::OnResuming(Platform::Object^ sender, Platform::Object^ args)
{
// Restore any data or state that was unloaded on suspend. By default, data
// and state are persisted when resuming from suspend. Note that this event
// does not occur if the app was previously terminated.
 m_renderer->CreateWindowSizeDependentResources();
}

IFrameworkView^ Direct3DApplicationSource::CreateView()
{
return ref new WindowsPhoneGame();
}

[Platform::MTAThread]
int main(Platform::Array<Platform::String^>^)
{
auto direct3DApplicationSource = ref new Direct3DApplicationSource();
CoreApplication::Run(direct3DApplicationSource);
return 0;
}

person Pectus Excavatum    schedule 28.05.2013    source источник
comment
Это, вероятно, вызвано количеством используемых вами пространств имен (загрязняющих глобальное пространство имен), попробуйте вместо этого использовать их в областях.   -  person Floris Velleman    schedule 29.05.2013
comment
Пространства имен существуют, чтобы избежать такого рода проблем. Смешивание всего вместе со всеми этими объявлениями using противоречит их цели. Не делай этого. Между прочим, эти ref new и object^ не C++.   -  person Pete Becker    schedule 29.05.2013
comment
Это С++/CLI. К сожалению. См. аналогичную проблему с предложением, которое может вам помочь - stackoverflow.com /вопросы/15767146/   -  person SChepurin    schedule 29.05.2013
comment
@JerryCoffin, я считаю, что это C++/CX, а не C++/CLI. Обратите внимание на ref new (C++/CLI использует gcnew). Эти два языка имеют почти идентичный синтаксис.   -  person Matt Smith    schedule 29.05.2013
comment
@MattSmith: Спасибо, моя ошибка.   -  person Jerry Coffin    schedule 29.05.2013


Ответы (2)


Вы используете много пространств имен. Казалось бы, что

EventRegistrationToken

определяется в

Windows::Foundation; //windows.winmd

И снова в eventtoken.h. Не уверен, к какому пространству имен это относится, может быть глобальным. Бросьте

using namespace Windows::Foundation;

а затем вы можете получить доступ к соответствующим реализациям следующим образом:

//eventtoken.h impl
EventRegistrationToken();

//the one in Foundation namespace:
Windows::Foundation::EventRegistrationToken();

Хотя похоже, что вам эта функция не нужна, так что может и не важно, это просто для примера, и для того как... раз вам нужно убрать это пространство имен, как теперь можно получить доступ к другим членам этого пространства имен.

Я предполагаю, что вы можете безопасно сделать это, хотя я не обязательно рекомендую это:

using namespace Windows;
Foundation::EventRegistrationToken();
person ChrisCM    schedule 28.05.2013

У меня была такая же проблема только с проектами WP8 SDK.

Исправление: удалите использование Windows::Foundation из файла .h и используйте полное пространство имен для вызова ваших типов объектов.

Windows::Foundation::IAsyncOperation<String^> ^Blah();

вместо

IAsyncOperation<String^> ^CreateSampleData();
person snickler    schedule 19.07.2014