Ошибка c2039 c

GBIT

14 / 14 / 5

Регистрация: 05.10.2011

Сообщений: 223

1

02.02.2013, 17:02. Показов 11198. Ответов 8

Метки нет (Все метки)


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

итак:
делаю MFC проект. Собственные функции пишу в отдельном MyLibrary.cpp к которому еще прилагается MyLibrary.h.
функция написана, компилится, а вот в h файле вылетают ошибки

Код

error C2039: list: не является членом "std"
error C2143: синтаксическая ошибка: отсутствие ";" перед "<"
error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию

MyLibrary.cpp

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
27
28
29
30
31
32
#include "StdAfx.h"
#include <Windows.h>
#include <list>
 
class Computer
{
public:
    int num;
    CString ip;
    CString mac;
    CString nbn;
    CString comment;
};
 
bool ReadItem (HANDLE hFile, int &num, CString &ip, CString &mac, CString &nbn, CString &comment)
{
// содержимое не важно
    return true;
}
 
std::list<Computer> ReadDB (HANDLE hFile)
{
    Computer    obj;
    std::list<Computer> items;
 
    while(ReadItem(hFile, obj.num, obj.ip, obj.mac, obj.nbn, obj.comment))
    {
        items.push_back(obj);
    }
 
    return items;
}

MyLibrary.h

C++
1
2
3
4
5
6
7
# ifndef MyLibrary_H
# define MyLibrary_H
 
HANDLE Open_File();
std::list<Computer> ReadDB (HANDLE hFile);
 
# endif

переписал все это дело в один файл и проект консольный зафигачил вроде все ок, а вот в разбивке по файлам не работает



0



Каратель

Эксперт С++

6608 / 4027 / 401

Регистрация: 26.03.2010

Сообщений: 9,273

Записей в блоге: 1

02.02.2013, 17:08

2

#include <list> переместить из cpp файла в хедер MyLibrary.h



0



14 / 14 / 5

Регистрация: 05.10.2011

Сообщений: 223

02.02.2013, 18:18

 [ТС]

3

просто перемещение не решает проблему,
скопировал инклуду в MyLibrary.h — появилась ошибка:

Код

error C2065: Computer: необъявленный идентификатор

зы. истина вот уже где-то рядом, но я в упор не понимаю



0



Каратель

Эксперт С++

6608 / 4027 / 401

Регистрация: 26.03.2010

Сообщений: 9,273

Записей в блоге: 1

02.02.2013, 18:19

4

ах да и класс Computer тоже перенесите



0



14 / 14 / 5

Регистрация: 05.10.2011

Сообщений: 223

02.02.2013, 18:25

 [ТС]

5

если делаю просто перенос, то результат так же как и в случае с переносом include <list> — опять не объявленные идентификаторы.
а вот копирование — оно решает вопрос.

только тут рождается новый вопрос: а вот такое дублирование(копирование) это верно? подозрение, что что-то тут не так



0



Jupiter

Каратель

Эксперт С++

6608 / 4027 / 401

Регистрация: 26.03.2010

Сообщений: 9,273

Записей в блоге: 1

02.02.2013, 18:34

6

MyLibrary.h

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#ifndef MyLibrary_H
#define MyLibrary_H
 
#include <Windows.h>
#include <list>
 
class Computer
{
public:
    int num;
    CString ip;
    CString mac;
    CString nbn;
    CString comment;
};
 
HANDLE Open_File();
std::list<Computer> ReadDB (HANDLE hFile);
 
#endif

MyLibrary.cpp

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include "StdAfx.h"
#include "MyLibrary.h" 
bool ReadItem (HANDLE hFile, int &num, CString &ip, CString &mac, CString &nbn, CString &comment)
{
// содержимое не важно
    return true;
}
 
std::list<Computer> ReadDB (HANDLE hFile)
{
    Computer    obj;
    std::list<Computer> items;
 
    while(ReadItem(hFile, obj.num, obj.ip, obj.mac, obj.nbn, obj.comment))
    {
        items.push_back(obj);
    }
 
    return items;
}



1



14 / 14 / 5

Регистрация: 05.10.2011

Сообщений: 223

02.02.2013, 18:42

 [ТС]

7

Код

fatal error C1083: Не удается открыть файл включение: MyLibrary.h: No such file or directory

расположение MyLibrary.h там же где и остальные все cpp и h файлы проекта (т.е. по умолчанию)



0



Каратель

Эксперт С++

6608 / 4027 / 401

Регистрация: 26.03.2010

Сообщений: 9,273

Записей в блоге: 1

02.02.2013, 18:47

8

Цитата
Сообщение от GBIT
Посмотреть сообщение

расположение MyLibrary.h там же где и остальные все cpp и h файлы проекта (т.е. по умолчанию)

а вроект он добавлен? в обозревателе решений он есть?



0



14 / 14 / 5

Регистрация: 05.10.2011

Сообщений: 223

02.02.2013, 20:05

 [ТС]

9

конечно

другие то функции отрабатывают из MyLibrary.cpp. (просто удалил когда скидывал сюда)

+ в файле …Dlg.cpp MFC проекта подключен #include «MyLibrary.h» и там все ок

Добавлено через 1 час 13 минут
все. понял где накосячил.

перепутал <> и «». Спасибо!



0



  • Remove From My Forums
  • Вопрос

  • Hello,

    In the header file I have defined the following,

    namesapce test {

    a.h class a { public bool wsetLogFile (const std::wstring&); };

    }

    And in the cpp file, I had defined the method,

    a.cpp
    bool a::wsetLogFile (const std::wstring& fileName)
    {
    ...
    }

    so when complied, getting following error,

    1>a.cpp(155): error C2039: 'wsetLogFile' : is not a member of 'Test::a'
    1> a.h(47) : see declaration of 'Test::a'

    Please help me to resolve the issue, I am compiling the code with Unicode character set.

    Thanks,

    John

Ответы

  • Quite simply, you cannot have two overloaded functions that have the same parameter list and only differ with the return type.

    The solution is simple: make them two distinct functions, as in:

    std::ofstream& print (enLogLevel level
    		   ,enLogType Type
    		   ,const char* Module
    		   ,bool PrintDate = true);
    
    std::wofstream& wprint (enLogLevel level
    		   ,enLogType Type
    		   ,const char* Module
    		   ,bool PrintDate = true);

    Frankly, I think it makes the programmer’s intentions more obvious.

    • Помечено в качестве ответа

      31 октября 2012 г. 3:41

  • Hello,

     
    In the header file I have defined the following,

     
    namesapce test {a.h
    class a
    {
    public
    bool wsetLogFile (const std::wstring&);
    };}

     
    And in the cpp file, I had defined the method,

     
    a.cpp
    bool a::wsetLogFile (const std::wstring& fileName)
    {

    }
    so when complied, getting following error,

     
    1>a.cpp(155): error C2039: ‘wsetLogFile’ : is not a member of ‘Test::a’
    1> a.h(47) : see declaration of ‘Test::a’
    Please help me to resolve the issue, I am compiling the code with Unicode character set.

    This is obviously not your real code, because it contains numerous spelling and other errors.

     
    Always post your actual code.

     
    The following code compiles and runs for me:

     
    #include <string>

     
    namespace Test {

     
    class a
    {
    public:
        bool wsetLogFile (const std::wstring&);
    };

     
    }

     
    using namespace Test;

     
    bool a::wsetLogFile (const std::wstring& fileName)
    {
        return true;
    }

     
    int main()
    {
        a x;
        bool bReturn = x.wsetLogFile(L»log.txt»);
        return 0;
    }


    David Wilkinson | Visual C++ MVP

    • Помечено в качестве ответа
      Elegentin Xie
      31 октября 2012 г. 3:41

  • In the header file I have defined the following,

    namesapce test {

    a.h class a { so when complied, getting following error,

    1>a.cpp(155): error C2039: 'wsetLogFile' : is not a member of 'Test::a'
    1> a.h(47) : see declaration of 'Test::a'

    Dave already called attention to the presence of obvious
    errors in your code snippets which betray the fact that
    you tried to retype it into your posts here. Never do
    that — it just wastes time, effort and bandwidth. Always
    use Windows’ copy & paste to post the *actual* code you’re
    working with.

    In your code snippet you’ve shown this:

    namesapce test {

    Obviously «namesapce» is a typographical error in the
    post here, which probably isn’t in your actual code
    as it would trigger another error.

    Question: Does your *actual* code have «test» as the
    namespace?

    In your error messages you’ve shown this:

    ‘wsetLogFile’ : is not a member of ‘Test::a’

    Note «Test» not «test».

    Make sure you haven’t made capitalization errors in
    your actual code. Both C and C++ are case-sensitive
    languages. «Test» != ‘test»

    — Wayne

    • Помечено в качестве ответа
      Elegentin Xie
      31 октября 2012 г. 3:41

  • The issue got resolved,after creating the new header file with same details.

    • Помечено в качестве ответа
      John_IN
      27 октября 2012 г. 6:29

Я не могу скомпилировать свой код из-за таких ошибок:

Error C2039: 'difference_type' : is not a member of 'Player' c:\program files (x86)\
microsoft visual studio 12.0\vc\include\xutility 373 1 Football Simulator"Error C2039: 'iterator_category' : is not a member of 'Player'  c:\program files (x86)\
microsoft visual studio 12.0\vc\include\xutility 371 1 Football Simulator"

И так далее.

Эти сообщения не имеют ничего общего с тем, как исправить код или где у компилятора возникли проблемы, и он оставил мне код, который я сейчас не могу скомпилировать.
Есть одна конкретная проблема с моим кодом, и я получаю кучу бесполезных ошибок компилятора, и среди них полезная ошибка, которая говорит мне, где настоящая ошибка

https://www.dropbox.com/s/jr2lmqwvfurpnok/Football%20Simulator.rar?dl=0
Это то, что я мог собрать из своего кода.
Для справки, строки 371 xutility читайте

// TEMPLATE CLASS iterator_traits
template<class _Iter>
struct iterator_traits
{   // get traits from iterator _Iter
typedef typename _Iter::iterator_category iterator_category;
typedef typename _Iter::value_type value_type;
typedef typename _Iter::difference_type difference_type;
typedef difference_type distance_type;  // retained
typedef typename _Iter::pointer pointer;
typedef typename _Iter::reference reference;
};

Это мой stdafx.h

#pragma once

#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <algorithm>
#include <cassert>
#include <string>
#include <time.h>

И это мой Player.h Что отлично.

 #pragma once
#include "PlayerAttributes.h"enum Position{
GK,
FB,
CB,
DM,
CM,
FW,
MAX_POSITIONS
};

class Player
{
PlayerAttributes Attributes;
std::string m_sName;
int m_nAge;
Position m_ePosition;
std::string e_sTeamName;

public:

Player();
Player(int nDesiredAttributeValues);
//
Player(std::string sName, int nAge, Position ePosition);

Player(std::string sName, int nAge, Position ePosition, int nDesiredAttributeValues);
~Player();

friend std::ostream& operator<< (std::ostream &out, Player &cPlayer);
};

РЕДАКТИРОВАТЬ:
И, как указано ниже, фактическая ошибка лежит в файле team.cpp

Team::Team(int nNumberOfPlayers, int nAttributeValue){

acPlayer = new Player[nNumberOfPlayers];
std::fill(acPlayer[0], acPlayer[nNumberOfPlayers-1], nAttributeValue);  // error
nTeamSize = nNumberOfPlayers;
}

Ничего полезного не появилось в списке ошибок и в выводе, 5-е сообщение гласило:

1> team.cpp (13): см. Ссылку на создание шаблона функции ‘void std :: fill (_FwdIt, _FwdIt, const _Ty &) компилируется

Как я должен идентифицировать проблему как это? Мой предыдущий метод заключался в проверке первой ошибки и переходе к указанной строке, но в этот раз это не сработало.

Благодарю.

-1

Решение

Как указано в моем комментарии выше, ошибка отображается в окне вывода Visual Studio, вы просто ее не видели (по какой-то причине).

Ошибка утверждает это:

1>  team.cpp(13) : see reference to function template instantiation 'void std::fill<Player,int>(_FwdIt,_FwdIt,const _Ty &)' being compiled

Эта ошибка указывает на это в Team.cpp файл:

//Test Slow version
Team::Team(int nNumberOfPlayers, int nAttributeValue){

acPlayer = new Player[nNumberOfPlayers];
std::fill(acPlayer[0], acPlayer[nNumberOfPlayers-1], nAttributeValue);  // error
nTeamSize = nNumberOfPlayers;
}

Теперь, когда все это видят, мы можем рассказать вам, в чем проблема. std::fill Функция требует итераторов для первых двух параметров, но вы предоставили полностью разнесенные объекты, а не итераторы.

Исправление должно сделать это:

    std::fill(acPlayer, acPlayer + nNumberOfPlayers, nAttributeValue);

Указатель имеет те же черты, что и итератор, который удовлетворяет условиям, которые std::fill требует. Первоначальная проблема заключалась в том, что std::fill алгоритм применял operator++ итератору, и так как вы передали объект, который не имеет ++ определено, ошибка испущена.

Таким образом, вопреки вашим утверждениям в посте, это не «бессмысленные ошибки компилятора». Ошибка имеет смысл.

2

Другие решения

Пожалуйста, прочтите описание ошибки на https://msdn.microsoft.com/en-us/library/fdwb3fd7.aspx

Похоже, ваш код использует шаблон. В экземпляре шаблона где-то, difference_type а также iterator_category ожидаются от вашего класса. Это означает, что либо от вашего объекта класса ожидается предоставление этих методов, либо вы передаете неправильный тип функции или объекту шаблона.

Проверьте все ссылки / использование вашего класса, особенно в шаблонных функциях. Это поможет вам найти ошибку.

0

***UPDATE***
So i googled my error and determined error C2039 was a missing header file (that all i could find online) I have the required header files but it is still giving me the error:

Error 1: error C2039: ‘getline’ : is not a member of ‘std::basic_ofstream<char,std::char_traits<char>>’

I still cannot figure out what i am doing wrong. Can anyone point me in the write direction?

I need to write a program to open a file and display it to the screen. Im having issues with line 39. I am not quite sure how to display each line of text in the file i have opened. And also how would i make the program only display 24 lines of the opened file at a time? I want the user to hit enter before i show more text from the opened file. I can also post the file if needed but its just basically a random story or something. Any help would be appreciated! thank you.

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
 //Chapter 12 Program 1
//Reads data from one file and displays it
//Written by 

#include <iostream>
#include <fstream> 
#include <string>

using namespace std; 

//Global constant
ofstream shipText;

//Function prototype
void showFile(ofstream &);

int main()
{ 
	shipText.open("shipText.txt", ios::in);
	cout << " Opening file... " << endl; 

	//If file open failed notify the user
	if (shipText.fail())
	{
		cout << " There was an unknown error and the file could not be opened. ";
	}
	else //Display shipText
	{
		showFile(shipText);
		shipText.close();
		cout << " The file has been displayed and is now closed. ";
	}
}

//************************************************************************************************
//ShowFile function to display shipText                                                          *
//************************************************************************************************

void showFile(ofstream &file)
{
	string textLine; 
	int counter = 0; 
	char textCh();

	while (!shipText.eof())
		if (counter > 24)
		{
			textCh();
			counter = 0;
		}

	getline(shipText, textLine, '\n');
	cout << textLine << endl;
	counter++;
}

Last edited on

The getline() function expects an input stream not an output stream.

Why is shipText a global variable? You’re passing it into your functions so it really should be local to main().

I originally had the shipText in main() but i got errors in my function saying shipText was undefined so i switched it to a global variable and it solved the problem.

And also im still confused by getline. I want to get the lines from the text and display them in my program (24 lines at a time). So would i use something like outfile.put(char)? But that only copies one character. Thanks for your help and response!

***EDIT*** i wrote a simpler version of the program and it compiles but does not display anything. Why is that? I also places the txt file it is suppose to read from in the same folder as the cpp file. Here is my code. Help on either code would be much appreciated!

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
27
28
29
30
31
32
33
34
35
36
37
38
//Chapter 12 Program 1
//Reads data from one file and displays it
//Written by 

#include <iostream>
#include <fstream> 
#include <string>
using namespace std;

//Global constant
fstream shipText;


int main()
{
	string input;

	shipText.open("shipText.txt", ios::in);
	cout << " Opening file... " << endl;

	//If file open successful
	if (shipText)
	{
		getline(shipText, input);
	
		while (shipText)
		{
			cout << input << endl;
			getline(shipText, input);
		}
		shipText.close();
	}
	else
	{
		cout << " Error File coule not be opened. ";
	}
	return 0;
}

Last edited on

Why is shipText a global variable? This is a program with a single function there is no need for the global variables. Also it is not a constant.

What does your file contain?

Sorry i posted the wrong code. I fixed those issues, but im still having the same error. I believe its happening before my while loop. this is the file i am trying to display in my program.

No one is unaware of the name of that famous English shipowner, Cunard.
In 1840 this shrewd industrialist founded a postal service between Liverpool and Halifax, featuring three wooden ships with 400-horsepower paddle wheels and a burden of 1,162 metric tons.
Eight years later, the company’s assets were increased by four 650-horsepower ships at 1,820 metric tons, and in two more years, by two other vessels of still greater power and tonnage.
In 1853 the Cunard Co., whose mail-carrying charter had just been renewed, successively added to its assets the Arabia, the Persia, the China, the Scotia, the Java, and the Russia, all ships of top speed and, after the Great Eastern, the biggest ever to plow the seas.
So in 1867 this company owned twelve ships, eight with paddle wheels and four with propellers.
If I give these highly condensed details, it is so everyone can fully understand the importance of this maritime transportation company, known the world over for its shrewd management.
No transoceanic navigational undertaking has been conducted with more ability, no business dealings have been crowned with greater success.
In twenty-six years Cunard ships have made 2,000 Atlantic crossings without so much as a voyage canceled, a delay recorded, a man, a craft, or even a letter lost.
Accordingly, despite strong competition from France, passengers still choose the Cunard line in preference to all others, as can be seen in a recent survey of official documents.
Given this, no one will be astonished at the uproar provoked by this accident involving one of its finest steamers.
No one is unaware of the name of that famous English shipowner, Cunard.
In 1840 this shrewd industrialist founded a postal service between Liverpool and Halifax, featuring three wooden ships with 400-horsepower paddle wheels and a burden of 1,162 metric tons.
Eight years later, the company’s assets were increased by four 650-horsepower ships at 1,820 metric tons, and in two more years, by two other vessels of still greater power and tonnage.
In 1853 the Cunard Co., whose mail-carrying charter had just been renewed, successively added to its assets the Arabia, the Persia, the China, the Scotia, the Java, and the Russia, all ships of top speed and, after the Great Eastern, the biggest ever to plow the seas.
So in 1867 this company owned twelve ships, eight with paddle wheels and four with propellers.
If I give these highly condensed details, it is so everyone can fully understand the importance of this maritime transportation company, known the world over for its shrewd management.
No transoceanic navigational undertaking has been conducted with more ability, no business dealings have been crowned with greater success.
In twenty-six years Cunard ships have made 2,000 Atlantic crossings without so much as a voyage canceled, a delay recorded, a man, a craft, or even a letter lost.
Accordingly, despite strong competition from France, passengers still choose the Cunard line in preference to all others, as can be seen in a recent survey of official documents.
Given this, no one will be astonished at the uproar provoked by this accident involving one of its finest steamers.
No one is unaware of the name of that famous English shipowner, Cunard.
In 1840 this shrewd industrialist founded a postal service between Liverpool and Halifax, featuring three wooden ships with 400-horsepower paddle wheels and a burden of 1,162 metric tons.
Eight years later, the company’s assets were increased by four 650-horsepower ships at 1,820 metric tons, and in two more years, by two other vessels of still greater power and tonnage.
In 1853 the Cunard Co., whose mail-carrying charter had just been renewed, successively added to its assets the Arabia, the Persia, the China, the Scotia, the Java, and the Russia, all ships of top speed and, after the Great Eastern, the biggest ever to plow the seas.
So in 1867 this company owned twelve ships, eight with paddle wheels and four with propellers.
If I give these highly condensed details, it is so everyone can fully understand the importance of this maritime transportation company, known the world over for its shrewd management.
No transoceanic navigational undertaking has been conducted with more ability, no business dealings have been crowned with greater success.
In twenty-six years Cunard ships have made 2,000 Atlantic crossings without so much as a voyage canceled, a delay recorded, a man, a craft, or even a letter lost.
Accordingly, despite strong competition from France, passengers still choose the Cunard line in preference to all others, as can be seen in a recent survey of official documents.
Given this, no one will be astonished at the uproar provoked by this accident involving one of its finest steamers.

This is my code:

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
27
28
29
30
31
32
33
34
35
36
37
38
39
//Chapter 12 Program 1
//Reads data from one file and displays it
//Written by 

#include <iostream>
#include <fstream> 
#include <string>
using namespace std;


int main()
{
	//Variables 
	string input;
	fstream shipText;

	//Open the file
	shipText.open("shipText.txt", ios::in);
	cout << " Opening file... " << endl;

	//If file open successful
	if (shipText)
	{
		cout << " Opening the file was a success! ";
		getline(shipText, input);
		
		while (shipText)
		{
			cout << input << endl;
			getline(shipText, input);
		}
		shipText.close();
	}
	else
	{
		cout << " Error File coule not be opened. ";
	}
	return 0;
}

Last edited on

I can’t reproduce your problems. The program seems to run and produce the desired output.

Do you get the error message «Error File coule not be opened»?

Also note your program could be simplified slightly:

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
27
28
29
30
#include <iostream>
#include <fstream>
#include <string>
using namespace std;


int main()
{
	//Variables
	string input;
	ifstream shipText("shipText.txt", ios::in);

	cout << " Opening file... " << endl;

	//If file open successful
	if (shipText)
	{
		cout << " Opening the file was a success! ";

		while(getline(shipText, input))
		{
			cout << input << endl;
		}
	}
	else
	{
		cout << " Error File coule not be opened. ";
	}
	return 0;
}

And note that depending on how you ran the program the current working directory can be at a location different that you seem to expect. If you’re running the program through the command line then the file needs to be in the location of the executable which may be different than where the .cpp file is located.

Last edited on

Most of my problems came from my first code. My second code compiles but doesnt display anything. It displays «opening the file was a success» however once i press enter to continue the program closes. Im also running it through MS visual studio without debugging.

I see the changes you made to the if statement to make it more simple. It makes it a lot easier to understand! I need to improve my programming style. Thanks for your help!

My final question is now that my program has read the contents of ShipText how would i output that to a brand new file? Would i use outfile.put(input) after line 22 or between 29 and 30 (in my code) i didnt want to copy your work to turn in so i didnt make those changes.

And also THANK YOU SOOOOOOOOOOOO MUCH!!! You have helped me a lot and i truly appreciate you taking the time out of your day to help a struggling student :)

Last edited on

If you can print the information to the screen properly, then printing to a file is almost identical. Read the line then print the line using the output stream insertion operator<<.

That sounds simple enough. Thank You! I still wasnt able to see my program run properly. It still exits when i press enter after opening the file and not displaying anything. How did you run the code? Was it also through visual studio? I also placed the shipText file in the same folder as the .exe but still no luck.

***EDIT***
So i looked into my shipText document and realized i did not press save when i put the story in so it was just a blank document LOL thats why it was nnot displaying anything. I forgot to hit save twice! But thanks for your help!

Last edited on

Topic archived. No new replies allowed.

Понравилась статья? Поделить с друзьями:
  • Ошибка c2010 kyocera 2040
  • Ошибка c2200 мицубиси
  • Ошибка c200d62 mazda
  • Ошибка c2200 додж калибр
  • Ошибка c200d mazda 6 gh