What’s wrong with this line of code?
bar foo(vector ftw);
It produces
error C2061: syntax error: identifier 'vector'
bdonlan
223k30 gold badges267 silver badges324 bronze badges
asked Jun 11, 2010 at 22:04
Nick HeinerNick Heiner
118k187 gold badges474 silver badges698 bronze badges
try std::vector instead. Also, make sure you
#include <vector>
answered Jun 11, 2010 at 22:06
Adrian GrigoreAdrian Grigore
33k36 gold badges130 silver badges210 bronze badges
Probably you forgot to include vector and/or import std::vector
into the namespace.
Make sure you have:
#include <vector>
Then add:
using std::vector;
or just use:
bar foo(std::vector<odp> ftw);
answered Jun 11, 2010 at 22:06
Matthew FlaschenMatthew Flaschen
277k50 gold badges514 silver badges538 bronze badges
1
Do you have:
#include <vector>
and
using namespace std;
in your code?
<vector>
defines the std::vector
class, so you need to include it some where in your file.
since you’re using vector
, you need to instruct the compiler that you’re going to import the whole std
namespace (arguably this is not something you want to do), via using namespace std;
Otherwise vector should be defined as std::vector<myclass>
answered Jun 11, 2010 at 22:06
try std::vector<odp>
or using std;
answered Jun 11, 2010 at 22:06
TreDubZeddTreDubZedd
2,5511 gold badge15 silver badges20 bronze badges
On its own, that snippet of code has no definition of bar
, vector
or odp
. As to why you’re not getting an error about the definition of bar
, I can only assume that you’ve taken it out of context.
I assume that it is supposed to define foo
as a function, that vector
names a template and that it is supposed to define a parameter called ftw
but in a declaration anything that is not actually being defined needs to have been declared previously so that the compiler knows what all the other identifiers mean.
For example, if you define new types as follows you get a snippet that will compile:
struct bar {};
struct odp {};
template<class T> struct vector {};
bar foo(vector<odp> ftw);
answered Jun 11, 2010 at 22:07
CB BaileyCB Bailey
747k102 gold badges631 silver badges655 bronze badges
Синтаксическая ошибка: идентификатор «Player». Файл mob.h ст 40
Гуглить пробовал. Ответ так и не нашел
player.h:
#pragma once
#include "Weapon.h"
#include "Mob.h"
class Player
{
public:
int health, armor, exp, mana;
int currentHealth, currentArmor, currentMana, toNextLvlExp, balance;
int missChanceBody, missChanceHead, missChanceLegs;
Weapon sword;
Weapon magicStick;
Player(int _health, int _armor, const Weapon& _sword, const Weapon& _magicStick);
int takePhysicalDamage(Mob& m);
};
mob.h:
#pragma once
#include <string>
#include "Player.h"
using namespace std;
class Mob
{
public:
enum mobType {
PHYSIC,
MAGIC
};
enum attackDir {
HEAD,
BODY,
LEGS
};
int health, armor, magicResistance, shockResistance;
int currentHealth, damage, spreadDamage;
string name;
mobType attackType;
/**
* Конструктор класса Mob.
* Принимает 3 аргумента
* _health - здоровье моба
* _magicResistance - защита от магического урона
* _shockResistance - защита от физического урона
* _damage - урон
* _spreadDamage - Разброс урона
* _name - Имя моба
* type - тип атаки моба
*/
Mob(int _health, int _magicResistance, int _shockResistance, int _damage, int _spreadDamage, string _name, mobType type);
int takePhysicalDamage(Player* player, attackDir dir);
int takeMagicalDamage(Player* player, attackDir dir);
};
I hate to post something so subtle, but this has me completely stumped on what I am doing wrong:
When I compile, it’s not liking Class Simulator at all. I get the error
syntax error : identifier 'Simulator'
at every instance of Simulator I use inside the DOCO header file. It also does this for my Pellet struct. The code was working completely fine until I started adding functions that work with the Simulator class inside DOCO.h.
The Simulator class uses the DOCO struct and the DOCO struct is using class Simulator. Is that a problem? Maybe I used included my headers wrong?
Here is a link to the error I get if it helps: http://msdn.microsoft.com/en-us/library/yha416c7.aspx
#include <iostream>
#include <conio.h>
#include <string>
#include "Simulator.h" //<---Has a chain of includes for other header files
int main()
{
RandomNumberGen R;
Simulator S;
Pellet P;
DOCO D;
system("pause");
return 0;
}
Header Files:
Simulator.h
#pragma once
#include <iostream>
#include <stdio.h>
//#include <conio.h>
#include <vector>
#include "Pellet.h"
#include "DataParser.h"
#include "DOCO.h"
#include "RandomNumberGen.h"
#include "Cell.h"
#include "Timer.h"
using namespace std;
class Simulator
{
private:
int s_iDocoTotal;
int s_iPelletTotal;
int s_iGridXComponent;
int s_iGridYComponent;
int tempX;
int tempY;
//Pellet P;
//DOCO D;
static const unsigned int s_iNumOfDir=8;
public:
Simulator();
~Simulator();
//int GenerateDirection();
void InitiateDOCO(RandomNumberGen *R, DOCO *D, vector<DOCO>&); //
void SpreadFood(RandomNumberGen *R, Pellet *P, vector<Pellet>&, const int x, const int y); //
void AddPellet(Pellet *P, RandomNumberGen *R); //
void CheckClipping(Pellet *P, RandomNumberGen *R); //
void CheckPellets(Pellet *P, RandomNumberGen *R); //
void CreateGrid(int x, int y);//
int GetGridXComponent(); //
int GetGridYComponent(); //
int GetDocoTotal();
vector<DOCO> docoList; //Holds the Doco coordinates
vector<Pellet> pelletList; //!!Dont use this!! For data import only
vector<vector<int> > pelletGrid; //Holds X-Y and pellet count
char **dataGrid; //Actual array that shows where units are
Simulator(const int x, const int y) :
s_iGridXComponent(x),
s_iGridYComponent(y),
pelletGrid(x, vector<int>(y)){}
};
DOCO.h
#pragma once
#include <iostream>
#include <stdio.h>
#include <vector>
#include "Simulator.h"
//#include "DataParser.h"
using namespace std;
struct DOCO
{
private:
int d_iXLocation;
int d_iYLocation;
int d_iEnergy;
int d_iMovement;
int d_iTemp;
//Simulator S;
//RandomNumberGen R;
//Pellet P;
enum Direction { NORTH, SOUTH, EAST, WEST, NORTHWEST, NORTHEAST, SOUTHWEST, SOUTHEAST};
public:
DOCO();
~DOCO();
//int a is the position in docoList to reference DOCO
int GoNorth(Simulator *S, int a);
int GoSouth(Simulator *S, int a);
int GoEast(Simulator *S, int a);
int GoWest(Simulator *S, int a);
int GoNorthWest(Simulator *S, int a);
int GoNorthEast(Simulator *S, int a);
int GoSouthWest(Simulator *S, int a);
int GoSouthEast(Simulator *S, int a);
//int a is the position in docoList to reference DOCO
void Sniff(Simulator *S, RandomNumberGen *R, int a); //Detects DOCOs and food
void Reroute(Simulator *S, RandomNumberGen *R, int a); //Changes DOCO direction
void SetDOCO(int tempX, int tempY, int tempEnergy, int tempMovement);
int GetEnergy(); //
int SetEnergy();
int SetMovement();
int GetMovement(); //
int GetXLocation(); //
int GetYLocation(); //
void SetXLocation(int d_iTemp);
void SetYLocation(int d_iTemp);
void EatPellet(Pellet *P, Simulator *S, int a);//ADD DOCO ARGUMENT / DONT OVERLAP DOCO AND PELLETS
void MoveDoco(Simulator *S, int a);
void Death();
};
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 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 |
#include <iostream> using namespace std; class book { private: char *author; char *title; char *publishing; unsigned int year; int num_pages; public: book():author(NULL),title(NULL),publishing(NULL),year(0),num_pages(0){} book(char *cur_author , char *cur_title , char *cur_publishing , unsigned int cur_year , int cur_num_pages); void set_author(char *cur_author); void set_title(char *cur_title); void set_publishing(char *cur_publishing); void set_year(unsigned int cur_year); void set_num_pages(int cur_num_pages); void board(); char *get_author(); char *get_title(); char *get_publishing(); unsigned int get_year(); int get_num_pages(); ~book(); }; class search { private: book *arr; int n; public: search(int n); void book_spisok(int n, char author); void book_npublishing(); void book_year(unsigned int year); ~search(); }; book :: ~book() { delete[]author; delete[]title; delete[]publishing; } book::book(char *cur_author , char *cur_title , char *cur_publishing , unsigned int cur_year , int cur_num_pages) : num_pages(cur_num_pages), year(cur_year) { author = new char[strlen(cur_author) + 1]; strcpy(book::author, cur_author); title = new char[strlen(cur_title) + 1]; strcpy(book::title, cur_title); publishing = new char[strlen(cur_publishing) + 1]; strcpy(book::publishing, cur_publishing); this -> year = cur_year; this ->num_pages = cur_num_pages; } void book::set_author(char *au) { delete[] author; author = new char[strlen(au) + 1]; strcpy(book::author, au); } void book::set_title(char *tl) { delete[] title; title = new char[strlen(tl) + 1]; strcpy(book::title, tl); } void book::set_publishing(char *ph) { delete[] publishing; publishing = new char[strlen(ph) + 1]; strcpy(book::publishing, ph); } void book::set_year(unsigned int yr) { this -> year = yr; } void book::set_num_pages(int num) { this -> num_pages = num; } char *book :: get_author() { return this -> author; } char *book :: get_title() { return this-> title; } char *book :: get_publishing() { return this-> publishing; } unsigned int book :: get_year() { return this-> year; } int book :: get_num_pages() { return this-> num_pages; } void book::board() { printf("nn Author - %s; Title - %s; Publishing - %s;n Year - %i. Number os pages - %inn", author, title, publishing, year, num_pages); } search::search(int n) { this -> n = n; char *authors[] = { "Koval", "Baden", "Kranchenko", "Finiak", "Abakumov", "Sorokin", "Savchenko", "Podgorniy" }; char *publishings[] = { "Bogdan", "LAZ", "Mersedes", "Volvo", "TATA" }; char *titles[] = { "Koval", "Baden", "Kranchenko", "Finiak", "Abakumov", "Sorokin", "Savchenko", "Podgorniy" }; arr = new book [n]; for (int i = 0; i<n; i++) { arr[i].set_author(authors[rand() % 8]); arr[i].set_publishing(publishings[rand() % 5]); arr[i].set_title(titles[rand() % 8]); arr[i].set_year(rand() % 27 + 1987); arr[i].set_num_pages(rand() % 10 + 100); arr[i].board(); cout << endl; } } void search::book_year(unsigned int year) { int k = 0; for (int i = 0; i < n; i++) { if (arr[i].get_year() > year) { cout << endl << "year > " << arr[i].get_title() << endl; k++; } } if (!k) cout << endl << "" << endl; } search::~search() { delete[]arr; } int main() { setlocale(LC_ALL,"Rus"); int n, year; cout << "Количество книг: "; cin >> n; if (n > 0) { search massive(n); cout << "Год: "; cin >> year; massive.book_year(n); } else cout << "Введено неверное число книгn"; system("pause"); return 0; } |
Я пытаюсь изучать C ++, однако, параметр метода, который у меня есть в моем собственном классе, ведет себя неправильно. Когда он использует dataType типа int, он отлично работает без ошибок, но когда я пытаюсь изменить его на «string» dataType, программа вылетает с этой ошибкой.
Ошибка 1 ошибка C2061: синтаксическая ошибка: идентификатор ‘строка’ в файле temp.h ln
8 цв 1
Я использую следующие классы:
РАБОЧИЙ КОД
TesterClass.cpp // Точка входа
#include "stdafx.h"#include "Temp.h"
int _tmain(int argc, _TCHAR* argv[])
{
Temp tmp;
tmp.doSomething(7);
return 0;
}
Temp.h
#pragma once
class Temp
{
public:
Temp();
void doSomething(int blah);
};
Temp.cpp
#include "stdafx.h"#include "Temp.h"
#include <iostream>
#include <string>
using std::string;
Temp::Temp()
{
std::cout << "Entry" << std::endl;
string hi;
std::cin >> hi;
std::cout << hi << std::endl;
}
void Temp::doSomething(int blah)
{
std::cout << blah;
}
Сломанный код
Temp.h
#pragma once
class Temp
{
public:
Temp();
void doSomething(string blah);
};
Temp.cpp
#include "stdafx.h"#include "Temp.h"
#include <iostream>
#include <string>
using std::string;
Temp::Temp()
{
std::cout << "Entry" << std::endl;
string hi;
std::cin >> hi;
std::cout << hi << std::endl;
}
void Temp::doSomething(string blah)
{
std::cout << blah;
}
Когда я настраиваю параметр «blah» на строку, как в файле .h, так и в файле .cpp, возникает проблема.
Я огляделся, но ни один из ответов, похоже, не решил мою проблему. Я очень хотел бы помочь в этом, я вне идей. Я попытался переустановить C ++, возиться с:
using namepace std;
using std::string;
std::string instead of string
etc.
Если вы знаете, как решить мою проблему, я хотел бы услышать от вас. Я более чем рад предоставить больше информации.
-3
Решение
C ++ выполняет однопроходную компиляцию, поэтому std :: string необходимо объявить перед тем, как использовать его вообще — в том числе в заголовочном файле.
// Temp.h
#pragma once
#include <string>
class Temp
{
public:
Temp();
void doSomething(std::string blah);
};
Я бы посоветовал вам быть более точным в ваших заголовочных файлах при указании таких классов, потому что вы можете легко встретить другую библиотеку, которая определяет свою собственную string
и тогда вы столкнетесь с конфликтами имен. Спасти using
импортировать операторы для ваших файлов cpp.
0
Другие решения
У πάντα ῥεῖ был письменный ответ, спасибо!
Они сказали использовать std :: string при необходимости, а также #include <string>
в заголовочном файле.
0