Error c2039 string is not a member of std

I am having problems with a class I am writing. I have split the class into a .h file that defines the class and an .cpp file that implements the class. I receive this error in Visual Studio 2010

I am having problems with a class I am writing. I have split the class into a .h file that defines the class and an .cpp file that implements the class.

I receive this error in Visual Studio 2010 Express:

error C2039: ‘string’ : is not a member of ‘std’

This is the header FMAT.h

class string;

class FMAT {
public:
    FMAT(); 

    ~FMAT(); 

    int session();              

private:
    int manualSession();    
    int autoSession();      

    int     mode;       
    std::string instructionFile;    

};

This is the implementation file FMAT.cpp

#include <iostream>
#include <string>
#include "FMAT.h"

FMAT::FMAT(){

    std::cout << "manually (1) or instruction file (2)nn";
    std::cin >> mode;
    if(mode == 2){
        std::cout << "Enter full path name of instruction filenn";
        std::cin >> instructionFile;
    }

}

int FMAT::session(){

    if(mode==1){
        manualSession();
    }else if(mode == 2){
        autoSession();
    }

    return 1;
}

int FMAT::manualSession(){
    //more code
    return 0;
}

this is the main file that uses this class

#include "FMAT.h"

int main(void)
{
    FMAT fmat;      //create instance of FMAT class

    fmat.session();     //this will branch to auto session or manual session

}

My inability to fix this error is probably a result of me not understanding how to properly structure a class into separate files. Feel free to provide some tips on how to handle multiple files in a c++ program.

thanks for answer George P,
i install codeblocks 20.03 ,
i select «std:c++17» in language standard ,The error was resolved, but new errors

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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
 #include <Windows.h>
#include <iostream>
#include <string>
#include <TCHAR.H>
#include "main.h"

using namespace std;


DWORD jmpBackAddy;
 DWORD  buffer_ptr;
bool Hook(void * toHook, void * ourFunct, int len)
{
    if (len < 5)
    {
        return false;
    }
    else
    {

    }

    DWORD curProtection;
    VirtualProtect(toHook, len, PAGE_EXECUTE_READWRITE, &curProtection);

    memset(toHook, 0x90, len);

    DWORD relativeAddress = ((DWORD)ourFunct - (DWORD)toHook) - 5;

    *(BYTE*)toHook = 0xE9;
    *(DWORD*)((DWORD)toHook + 1) = relativeAddress; // <-- I DID NOT UNDERSTAND THIS

    DWORD temp;
    VirtualProtect(toHook, len, curProtection, &temp);

    return true;
}
//



//
void __declspec(naked) ourFunct()
{


    __asm{

mov esi,ecx
cmp eax,1000040
je codey
jmp code20


code20:
cmp eax,1001010
je codey
jmp code

codey:
mov eax,0
jmp code


hid:
mov eax,1001010
jmp code
code:
        mov dword ptr ds:[esi],eax
        lea eax,dword ptr ds:[edi+4]
		jmp jmpBackAddy
    }



}

DWORD WINAPI MainThread(LPVOID param)
{
    int hookLength = 7;//5 for jump + 3 remaining

   // DWORD hookAddress = 0x4E9DEA; // it's right

	DWORD hookAddress = 0x4E972C; // it's right
    jmpBackAddy = hookAddress + hookLength;
    Hook((void*)hookAddress, ourFunct, hookLength);


    return 0;
}
BOOL WINAPI DllMain(HINSTANCE hModule, DWORD dwReason, LPVOID lpReserved) {
	switch (dwReason) {
	case DLL_PROCESS_ATTACH:
		CreateThread(0, 0, MainThread, hModule, 0, 0);
		break;
	}

	return TRUE;
}

У меня проблемы с классом, который я пишу. Я разделил класс на файл .h, который определяет класс, и файл .cpp, который реализует класс.

Я получаю эту ошибку в Visual Studio 2010 Express:

ошибка C2039: ‘строка’: не является членом ‘std’

Это заголовок FMAT.h

class string;

class FMAT {
public:
    FMAT(); 

    ~FMAT(); 

    int session();              

private:
    int manualSession();    
    int autoSession();      

    int     mode;       
    std::string instructionFile;    

};

Это файл реализации FMAT.cpp

#include <iostream>
#include <string>
#include "FMAT.h"

FMAT::FMAT(){

    std::cout << "manually (1) or instruction file (2)nn";
    std::cin >> mode;
    if(mode == 2){
        std::cout << "Enter full path name of instruction filenn";
        std::cin >> instructionFile;
    }

}

int FMAT::session(){

    if(mode==1){
        manualSession();
    }else if(mode == 2){
        autoSession();
    }

    return 1;
}

int FMAT::manualSession(){
    //more code
    return 0;
}

это основной файл, который использует этот класс

#include "FMAT.h"

int main(void)
{
    FMAT fmat;      //create instance of FMAT class

    fmat.session();     //this will branch to auto session or manual session

}

Моя неспособность исправить эту ошибку, вероятно, является результатом того, что я не понимаю, как правильно структурировать класс в отдельные файлы. Не стесняйтесь дать несколько советов о том, как обрабатывать несколько файлов в программе на C ++.

Я использую VS2008 и Win7 64bit.

#include <iostream>
#include "utils.h"#include <string>

int main()
{
int gm = DETECT;
int gd = DETECT;
initgraph(&gm, &gd, "");
double x = 0;
double y = 0;
double r = 50;
for(int i=0 ; i<=360 ; i++)
{
x = r * cos(DegreeToRad((double)i));
y = r * sin(DegreeToRad((double)i));

PlotLine(0,0,x,y, YELLOW);

std::string str;
str.append(std::to_string(i));
str.append(". ");
str.append(std::to_string(0));
str.append(", ");
str.append(std::to_string(0));
str.append(") to (");
str.append(std::to_string(x));
str.append(", ");
str.append(std::to_string(y));
str.append(").  m=");
str.append(std::to_string(Slope(0,0,x,y)));
str.append("n");

if(i%90==0)
{
str.append("ni=");
str.append(std::to_string(i));
str.append("n");
}

WriteToFile("slope.txt", str.c_str());
}

getch();
closegraph();

return 0;
}

Сообщения об ошибках.

1>e:slope.test.cpp(21) : error C2039: 'to_string' : is not a member of 'std'
1>e:slope.test.cpp(21) : error C3861: 'to_string': identifier not found
1>e:slope.test.cpp(23) : error C2039: 'to_string' : is not a member of 'std'
1>e:slope.test.cpp(23) : error C3861: 'to_string': identifier not found
1>e:slope.test.cpp(25) : error C2039: 'to_string' : is not a member of 'std'
1>e:slope.test.cpp(25) : error C3861: 'to_string': identifier not found
1>e:slope.test.cpp(27) : error C2039: 'to_string' : is not a member of 'std'
1>e:slope.test.cpp(27) : error C3861: 'to_string': identifier not found
1>e:slope.test.cpp(29) : error C2039: 'to_string' : is not a member of 'std'
1>e:slope.test.cpp(29) : error C3861: 'to_string': identifier not found
1>e:slope.test.cpp(31) : error C2039: 'to_string' : is not a member of 'std'
1>e:slope.test.cpp(31) : error C3861: 'to_string': identifier not found
1>e:slope.test.cpp(37) : error C2039: 'to_string' : is not a member of 'std'
1>e:slope.test.cpp(37) : error C3861: 'to_string': identifier not found
1>Generating Code...
1>Build log was saved at "file://e:DebugBuildLog.htm"1>RasterizationLineCircleEllipse - 15 error(s), 14 warning(s)
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

-1

Решение

Эти ошибки могут означать:

  1. std :: to_string требует заголовка, который вы не включили (но не включили)
  2. Вы не включили C ++ 11 (я не знаю, как это работает для Visual Studio)
  3. Ваш компилятор не поддерживает C ++ 11.

Из комментариев кажется, что Visual Studio, которую вы используете, не поддерживает C ++ 11, поэтому вы можете использовать старый добрый поток строк и с шаблоном вы можете создать эквивалент std :: to_string:

#include <sstream>
#include <string>

template<class T>
std::string toString(const T &value) {
std::ostringstream os;
os << value;
return os.str();
}

//Usage:
std::string valueStr = toString(10);
valueStr.append(toString(1));
valueStr.append(toString(2.5));

Обратите внимание, что для использования этого типа функции T должен иметь operator<< определено, но это не проблема с типами, которые поддерживает std :: to_string.

4

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

Chempion

0 / 0 / 0

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

Сообщений: 27

1

23.03.2012, 09:29. Показов 7337. Ответов 8

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


Выдает вот такие ошибки

Employee.cpp(20) : error C2039: YearsofService: не является членом «Employee»
1> c:usersкварц3desktopstudentрешенные задачи по с++employeeemployeeEmployee.hpp(3): см. объявление ‘Employee’
1>.Employee.cpp(21) : error C2039: YearsofService: не является членом «Employee»
1> c:usersкварц3desktopstudentрешенные задачи по с++employeeemployeeEmployee.hpp(3): см. объявление ‘Employee’
1>.Employee.cpp(22) : error C2039: Salary: не является членом «Employee»
1> c:usersкварц3desktopstudentрешенные задачи по с++employeeemployeeEmployee.hpp(3): см. объявление ‘Employee’
1>.Employee.cpp(23) : error C2039: Salary: не является членом «Employee»
1> c:usersкварц3desktopstudentрешенные задачи по с++employeeemployeeEmployee.hpp(3): см. объявление ‘Employee’

, никак не пойму что сделать, есть предложения?
код программы:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "stdafx.h"
#include "Employee.hpp"
#include <iostream>
using namespace System;
Employee::Employee(int initialAge)
{
    itsAge = initialAge;
}
 
Employee::~Employee()
{
}
 
int main()
{
    Employee Jon(26);
    std::cout<<"Jon is a man who is "<< Jon.GetAge()<<"years old.n"<<std::endl;
    Jon.YearsofService(5);
    std::cout<<"Jon Years of Service = "<<Jon.YearsofService()<<"n"<<std::endl;
    Jon.Salary(30000);
    std::cout<<"Jon salary = "<<Jon.Salary()<<"n"<<std::endl;
    return 0;
}

Код класса:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
class Employee
{
public:
    Employee (int initialAge);
    ~Employee();
    int GetAge() const {return itsAge;}
    void SetAge (int Age) {itsAge=Age;}
    int GetYearsofService() const {return itsYearsofService;}
    void SetYearsofService(int YearsofService) {itsYearsofService=YearsofService;}
    int GetSalary() const {return itsSalary;}
    void SetSalary(int Salary) {itsSalary=Salary;}
private:
    int itsAge;
    int itsYearsofService;
    int itsSalary;
};

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



retmas

Жарю без масла

867 / 749 / 225

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

Сообщений: 1,702

23.03.2012, 09:46

2

C++
1
2
3
4
Jon.SetYearsofService(5);
std::cout<<"Jon Years of Service = "<<Jon.GetYearsofService()<<"n"<<std::endl;
Jon.SetSalary(30000);
std::cout<<"Jon salary = "<<Jon.GetSalary()<<"n"<<std::endl;



1



Black Fregat

Фрилансер

3703 / 2075 / 567

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

Сообщений: 6,683

23.03.2012, 10:00

3

C++
1
2
3
4
Jon.SetYearsofService(5);
std::cout<<"Jon Years of Service = "<<Jon.GetYearsofService()<<"n"<<std::endl;
Jon.SetSalary(30000);
std::cout<<"Jon salary = "<<Jon.GetSalary()<<"n"<<std::endl;

Добавлено через 1 минуту
Опоздал..



1



0 / 0 / 0

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

Сообщений: 27

23.03.2012, 10:33

 [ТС]

4

Сделал, появилась вот такая ошибка:
1>.Employee.cpp(21) : error C2660: Employee::SetYearsofService: функция не принимает 0 аргументов
1>.Employee.cpp(23) : error C2660: Employee::SetSalary: функция не принимает 0 аргументов



0



Жарю без масла

867 / 749 / 225

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

Сообщений: 1,702

23.03.2012, 10:39

5

ищите в программе гда вы вызываете эти ф-ии без параметра



1



0 / 0 / 0

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

Сообщений: 27

23.03.2012, 11:36

 [ТС]

6

И что с ними делать?) если в коде поищешь который выше, буду очень благодарен)



0



Фрилансер

3703 / 2075 / 567

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

Сообщений: 6,683

26.03.2012, 05:29

7

У Вас ведь на каждый параметр 2 разных функции доступа — для чтения и для записи.
Вы нигде не попутали Get…() и Set…(значение) ?
Чтение — без параметров, есть возвращаемое значение.
Запись — один параметр (новое значение), void.



1



0 / 0 / 0

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

Сообщений: 27

27.03.2012, 09:56

 [ТС]

8

Спасибо всем, нашел все ошибки и исправил) всё работает)



0



0 / 0 / 0

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

Сообщений: 28

02.01.2016, 12:56

9



0



Понравилась статья? Поделить с друзьями:
  • Error c2027 use of undefined type
  • Error c2026 string too big trailing characters truncated
  • Error c2011 переопределение типа class
  • Error c2011 timespec переопределение типа struct
  • Error c2001 newline in constant