C2872 ошибка c

Студворк — интернет-сервис помощи студентам

В общем вчера взялся изучать C++ по книге «C++ Базовый курс, 3 издание» Г. Шилдта.
И тут такая запара.

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;
void func1();
void func2();
int count;
 
int main()
{
    int i;
    for (i=0; i<10; i++) {
        count = i * 2;
        func1();
    }
    return 0;
}
void func1()
{
    func2();
    cout << "count: " << count;
    cout << 'n';
}
void func2()
{
    int count;
    for(count=0; count<3; count++) cout<< '.';
}

При попытке компилить, выдаёт -«error C2872: неоднозначный символ», дважды, на 11 и 19 строках, если же заменить «count» на «x», то компилит без проблем.
Может кто пояснить, что конкретно ему не нравится и почему этот пример (представленный в книге и 20 раз перепроверенный на очепятки) не работает в предоставленном автором виде?

Пользуюсь компилятором из Visual Studio 2012, версии 17.00.50727.1 для x86.

I keep having this issue with this program involving templates. I apologize for posting the entire code, but it’s extremely short. The problem I keep having is it claims there’s an error in c2872.

driver.cpp

#include <iostream>
#include "pair.h"
using namespace std;


int main()
{
    pair<char> letters('a', 'd');
    cout << "nThe first letter is: " << letters.getFirst();
    cout << "nThe second letter is: " << letters.getSecond();

    cout << endl;
    system("Pause");
    return 0;
}

Class .cpp file

#include "pair.h"

template <class T>
pair<T>::pair(const T& first, const T& second)
{
    f = first;
    s = second;
}

template<class T>
T pair<T>::getFirst() const
{
    return first;
}

template<class T>
T pair<T>::getSecond() const
{
    return second;
}

template<class T>
void pair<T>::setFirst(const T& first, const T& second)
{
    T temp = first;
    first = second;
    second = temp;
}

header file

template <class T>
class pair
{
private:
    T f;
    T s;
public:
    pair(const T&, const T&);
    T getFirst() const;
    T getSecond() const;
    void setFirst(const T&, const T&);
};

asked Apr 10, 2014 at 1:52

nelson2013's user avatar

3

There is already std::pair. Since you also go using namespace std;, the issue could be that compiler cannot tell whether you mean std::pair or your pair.

To fix this, either stop doing using namespace std; , or call your pair something else. Preferably both!

answered Apr 10, 2014 at 1:56

M.M's user avatar

M.MM.M

138k21 gold badges204 silver badges357 bronze badges

6

First, delete pair.cpp because templates can’t be defined in separate source files. Next, replace pair.h with this concatenated source from pair.cpp.

Pair.h

namespace notstd {

template <class T>
class pair
{
private:
    T f;
    T s;
public:
    pair(const T&, const T&);
    T getFirst() const;
    T getSecond() const;
    void setFirst(const T&, const T&);
};

template <class T>
pair<T>::pair(const T& first, const T& second)
{
    f = first;
    s = second;
}

template<class T>
T pair<T>::getFirst() const
{
    //return first; //possible error?
    return f;
}

template<class T>
T pair<T>::getSecond() const
{
    //return second; //possible error?
    return s;
}

template<class T>
void pair<T>::setFirst(const T& first, const T& second)
{
    T temp = first;
    first = second;
    second = temp;
}

} //end namespace notstd

Finally, delete using namespace std and add using notstd::pair, OR prepend all pair with notstd::pair.

Community's user avatar

answered Apr 10, 2014 at 2:30

Suedocode's user avatar

SuedocodeSuedocode

2,5043 gold badges22 silver badges41 bronze badges

  • Remove From My Forums
  • Question

  • Hi,
    I am getting the error
    ……ServProv.h(93) : error C2872: ‘IServiceProvider’ : ambiguous symbol

    with the following code.

    file.cpp

    #include «stdafx.h»

    using namespace System;
    using namespace System::Runtime::Remoting;
    #import «.RemotableObject.tlb»

    namespace mynamespace {
        class myclass {     …     }
        int _tmain(int argc, _TCHAR* argv[])
        {         return 0;     }
    }

    RemotableObject.tlb is generated from a c# dll.
    I am not using IServiceProvider directly in the file

    Based on a note in msdn library, I have moved the native header files to the top of the list. Even then I am getting the error.

    Help is tremendously appreciated.

    thanks

      GKM

Answers

  • Just to close my last post

    The error I had was

    c:Program FilesMicrosoft Visual Studio .NET 2003Vc7PlatformSDKIncludeServProv.h(47) : warning C4935: assembly access specifier modified from ‘public’
    c:Program FilesMicrosoft Visual Studio .NET 2003Vc7PlatformSDKIncludeServProv.h(92) : error C2872: ‘IServiceProvider’ : ambiguous symbol
            could be ‘c:Program FilesMicrosoft Visual Studio .NET 2003Vc7PlatformSDKIncludeServProv.h(47) : System::IServiceProvider IServiceProvider’
            or       ‘Form1.cpp(0) : System::IServiceProvider’
    c:Program FilesMicrosoft Visual Studio .NET 2003Vc7PlatformSDKIncludeServProv.h(99) : fatal error C1903: unable to recover from previous error(s); stopping compilation

    It was so frustrating becuase I hadn’t edited either of the two files listed.  This was solved was simply moving the #include <altstr.h> declaration (in a different file to either of the ones mentioned above) from below, to above the ‘using namespace’ directives

    e.g.

    #pragma once

    #using <mscorlib.dll>

    #include <windows.h>

    #include <atlstr.h>

    using namespace System;

    using namespace System::IO;

    using namespace System::Collections;

    using namespace System::Collections::Specialized;

    Once this was done, everything compiled and ran without a problem (other than the actual logic problems in my code…)

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Compiler Error C2872

Compiler Error C2872

11/04/2016

C2872

C2872

c619ef97-6e0e-41d7-867c-f8d28a07d553

Compiler Error C2872

symbol‘ : ambiguous symbol

The compiler cannot determine which symbol you are referring to. More than one symbol with the specified name is in scope. See the notes following the error message for the file locations and declarations the compiler found for the ambiguous symbol. To fix this issue, you can fully qualify the ambiguous symbol by using its namespace, for example, std::byte or ::byte. You can also use a namespace alias to give an included namespace a convenient short name for use when disambiguating symbols in your source code.

C2872 can occur if a header file includes a using directive, and a subsequent header file is included that contains a type that is also in the namespace specified in the using directive. Specify a using directive only after all your header files are specified with #include.

C2872 can occur in Visual Studio 2013 due to a conflict between the Windows::Foundation::Metadata::Platform enum type and the C++/CX-defined Platform namespace. To work around this problem, follow these steps:

  • Remove the «using namespace Windows::Foundation::Metadata» clause from the project files.

  • Specify the fully qualified name for any type that is included in this namespace.

Example

The following sample generates C2872, because an ambiguous reference is made to a variable named i; two variables with the same name are in scope:

// C2872.cpp
// compile with: cl /EHsc C2872.cpp
namespace A {
   int i;
}

using namespace A;
int i;
int main() {
   ::i++;   // ok, uses i from global namespace
   A::i++;   // ok, uses i from namespace A
   i++;   // C2872 ambiguous: ::i or A::i?
   // To fix this issue, use the fully qualified name
   // for the intended variable.
}

I have creating a new project and I am adding existing project reference and calling one class from the existing one. I am getting the below error — Error c2872 : ambiguous symbol

asked Oct 1, 2015 at 6:40

santhoshkumar kumaresan's user avatar

2

This happens when the compiler sees two identical symbols, e.g., you write your own cout in namespace yours, then use using namespace yours; and using namespace std;, and then use cout (without the namespace). The compiler is unable to identify which cout you actually meant. So in this situation you could use yours::cout.

answered Oct 1, 2015 at 7:57

13ushm4n's user avatar

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • C2785 ошибка мазда 3
  • C2778 ошибка форд фокус 2
  • C2762 ошибка приус 10
  • C2730 kyocera 5551 ошибка

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии