Timon32 0 / 0 / 0 Регистрация: 18.07.2015 Сообщений: 76 |
||||||||
1 |
||||||||
синтаксическая ошибка при определении функции шаблона02.12.2020, 19:10. Показов 1779. Ответов 8 Метки нет (Все метки)
Ошибка в определении Vector<T>::Iterator Vector<T>::Iterator::operator-(size_t i)const Вывод: .h
.inl
__________________ 0 |
Комп_Оратор) 8771 / 4510 / 608 Регистрация: 04.12.2011 Сообщений: 13,454 Записей в блоге: 16 |
|
02.12.2020, 19:15 |
2 |
Timon32, вы разделили описание шаблона на 2 файла? 0 |
Timon32 0 / 0 / 0 Регистрация: 18.07.2015 Сообщений: 76 |
||||||||||||
02.12.2020, 20:21 [ТС] |
3 |
|||||||||||
Да. На данный момент мне удалось побороть ошибку, но не тем путем которым я хотел. На данный момент код выглядит так: .hpp:
.inl :
main:
0 |
Комп_Оратор) 8771 / 4510 / 608 Регистрация: 04.12.2011 Сообщений: 13,454 Записей в блоге: 16 |
|
02.12.2020, 21:01 |
4 |
но не тем путем которым я хотел. Но тем путём которым и следовало. Шаблон это не чертёж для построения исполнимого кода. Это чертёж для построения исходного кода. Компоновщик не может слинковать код который не сгенерирован. Всё нужно писать в заголовочник в итоге) 0 |
0 / 0 / 0 Регистрация: 18.07.2015 Сообщений: 76 |
|
02.12.2020, 21:57 [ТС] |
5 |
Не один раз видел как выносят реализацию шаблонных функций в отдельный файл(.inl). 0 |
Комп_Оратор) 8771 / 4510 / 608 Регистрация: 04.12.2011 Сообщений: 13,454 Записей в блоге: 16 |
|
02.12.2020, 22:51 |
6 |
Не один раз видел как выносят реализацию шаблонных функций в отдельный файл(.inl). Явные специализации — можно, сам шаблон — нет. Когда-то пытались это сделать ( 0 |
0 / 0 / 0 Регистрация: 18.07.2015 Сообщений: 76 |
|
03.12.2020, 00:01 [ТС] |
7 |
0 |
Комп_Оратор) 8771 / 4510 / 608 Регистрация: 04.12.2011 Сообщений: 13,454 Записей в блоге: 16 |
|
03.12.2020, 00:23 |
8 |
Timon32, вы включаете файл в хедер. Я такого не видел и не имел ввиду. Тут скорее всего не идёт речь ни о какой раздельной компиляции. Потому что ваш ini файл не видит хедера и всё что в нём написано не будет распарсено компилятором в отдельной единице трансляции. Если ваш компилятор на стадии препроцессинга сразу сливает всё в один текст, то может оно и будет работать. 0 |
TheCalligrapher Вездепух 10420 / 5692 / 1550 Регистрация: 18.10.2014 Сообщений: 14,018 |
||||||||
03.12.2020, 00:47 |
9 |
|||||||
Сообщение было отмечено Timon32 как решение Решение
warning C4346: Iterator: зависимое имя не является типом Вам же сам компилятор ясно написал, что нужно сделать.
Что это вообще такое? 1 |
When I compile there is an error call «error C2061: syntax error : identifier ‘Player’ «
I can’t figure out what is wrong with my code. Here is my code
#include "Platform.h" #include "Player.h" class Collision { public: Collision(void); ~Collision(void); static bool IsCollision(Player &player, Platform& platform); };
There is an error in «IsCollision» method.
Player.h
#include <SFML/Graphics.hpp> #include "rapidxml.hpp" #include <fstream> #include <iostream> #include "Collision.h" using namespace rapidxml; class Player { private: sf::Texture playerTexture; sf::Sprite playerSprite; sf::Vector2u position; sf::Vector2u source; sf::Vector2u size; int frameCounter, switchFrame, frameSpeed; int walkSpriteWidth; float velocity; bool isWalk; bool isStand; bool isFaceRight; public: Player(void); ~Player(void); void Init(); void Draw(sf::RenderWindow *window); void MoveForward(); void MoveBackward(); void Update(sf::Clock *clock); void SetSourceY(int value); void SetWalk(bool value); void SetFacing(std::string value); void SetStand(bool value); void Stand(); std::string GetStatus(); void PrintStatus(); sf::Vector2f GetPosition(); int GetWidth(); int GetHeight(); };
georges619
2881 gold badge7 silver badges18 bronze badges
asked Apr 3, 2013 at 8:32
7
You have a circular include dependency. Collision.h includes Player.h and vice versa. The simplest solution is to remove #include "Collision.h"
from Player.h
, since the Collision
class is not needed in the Player
declaration. Besides that, it looks like some of your includes in Collision.h
can be replaced by forward declarations:
// forward declarations
class Player;
class Platform;
class Collision
{
public:
Collision(void);
~Collision(void);
static bool IsCollision(Player &player, Platform& platform);
};
You can then put the includes in Collision
‘s implementation file.
answered Apr 3, 2013 at 8:37
juanchopanzajuanchopanza
221k33 gold badges397 silver badges474 bronze badges
0
That’s a pretty common mistake — you have circular include dependency.
Looking at your code, you should replace #include "Player.h"
with class Player;
in Collision.h
. This is called «forward declaration» and will break the circular dependency.
Also, it would be good to add include guards, for example:
#ifndef MY_PLAYER_CLASS
#define MY_PLAYER_CLASS
...
#endif
And this should be done for each header you write.
answered Apr 3, 2013 at 8:37
Kiril KirovKiril Kirov
37.1k22 gold badges111 silver badges185 bronze badges
Circular dependency or you’re using a C compiler for C++ code
answered Apr 8, 2019 at 16:09
1
Синтаксическая ошибка: идентификатор «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);
};
Я пытаюсь изучать 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
Recommended Answers
Making your
FIGURE_TYPE
struct from yourFigure
class public can solve your problem. Presumably yourFIGURE_TYPE
is in the defauls private block of your class, which means you can’t access it directly. Making it public allows other classes to use that struct, even if it’s declared in …
Jump to Post
This might be basic, but have you included UI.h in the current file?
Jump to Post
All 5 Replies
10 Years Ago
Making your FIGURE_TYPE
struct from your Figure
class public can solve your problem. Presumably your FIGURE_TYPE
is in the defauls private block of your class, which means you can’t access it directly. Making it public allows other classes to use that struct, even if it’s declared in the Figure
class.
Here’s a small example:
#include <iostream> using namespace std; #define NR 5 class SDL_Rect{}; class A{ public: struct FIGURE_TYPE { SDL_Rect crop; int x; int y; }; }; class B{ public: void printFig(A::FIGURE_TYPE figure_index[NR]){ for (int i=0;i<NR;i++){ cout<<"X: "<<figure_index[i].x<<" Y: "<<figure_index[i].y<<endl; } } }; int main(){ A::FIGURE_TYPE figs[NR]; for (int i=0;i<NR;i++){ figs[i].x=i+10; figs[i].y=i+20; } B().printFig(figs); return 0; }
10 Years Ago
It is public. Any other ideas?
Thank you for taking an interest, by the way.
10 Years Ago
This might be basic, but have you included UI.h in the current file?
10 Years Ago
It turns out I had a circular dependency with my headers. Thank you for helping though!
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
Ok, real simple. I declared all my veriable properly. I have tried this code before on another example. I am using academic edition just because I want to learn and try some programming stuff for fun. Then I hit this stupid brick
wall. Read Below.
Int16 upperlimitregular; // regular numbers
Int16 upperlimitbonus; // bonus numbers
Int16 bonusnuma;
Int16 num1a;
Int16 num2a;
Int16 num3a;
Int16 num4a;
Int16 num5a;
Int16 i;
#pragma endregion
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e)
{
num1a = 0;
num2a = 0;
num3a = 0;
num4a = 0;
num5a = 0;
// clear bonus number
bonusnuma = 0;
}
private: System::Void btnStart_Click(System::Object^ sender, System::EventArgs^ e)
{
// check numeric
//String^ strNumOfPlay;
Int16 dblNumOfPlay;
if(txtbxNumOfPlay->Text->Length > 0)
{
if(Double::TryParse(txtbxNumOfPlay->Text, dblNumOfPlay))
{
Int16 intNumOfPlay = dblNumOfPlay;
MegaMillion(intNumOfPlay);
}
else
{
txtbxResults->Text = «Number of plays must be numeric.»;
}// end if other then a number is inputted.
}// end if blank
else
{
txtbxResults->Text = «Please enter a number.»;
}// end if blank
}// end btnstart
private: Void MegaMillion(Int16 dblNumOfPlay)
{
DateTime moment = DateTime::Now;
Random^ randNumGen = gcnew Random(moment.Millisecond);
//
upperlimitregular = 56; // regular numbers
upperlimitbonus = 46;
//
// start do loop for 1 game, using the number of plays to stop the process.
// have to look up do loops again.
do while(i=0, i++, i=dblNumOfPlay)
{
// clear game for next game.
// clear array
num1a = 0;
num2a = 0;
num3a = 0;
num4a = 0;
num5a = 0;
// clear bonus number
bonusnuma = 0;
// get Randomize number
num1a = randNumGen->Next(upperlimitregular);
num1a += 1;
num2a = randNumGen->Next(upperlimitregular);
num2a += 1;
do while(num2a == num1a)
{
num2a = randNumGen->Next(upperlimitregular);
} // end number 2
num3a = randNumGen->Next(upperlimitregular);
num3a +=1;
do while(num3a == num1a || num3a == num2a)
{
num3a = randNumGen->Next(upperlimitregular);
}// end number 3
num4a = randNumGen->Next(upperlimitregular);
num4a += 1;
do while(num4a == num1a || num4a == num3a || num4a == num2a || num4a == num1a)
{
num4a = randNumGen->Next(upperlimitregular);
}// end number 4
num5a = randNumGen->Next(upperlimitregular);
num5a += 1;
do while(num5a == num4a || num5a == num3a || num5a == num2a || num5a == num1a)
{
num5a = randNumGen->Next(upperlimitregular);
}// end number 5
// Select 1 bonus number
bonusnuma = randNumGen->Next(upperlimitbonus);
bonusnuma +=1;
// Display results in result box
txtbxResults->Text = num1a.ToString(),» «, num2a.ToString(),» «,
num3a.ToString(),» «,num4a.ToString(),» «,
num5a.ToString(),» «,bonusnuma.ToString(), «/r/r/n»;
// Add numbers to database.
} // end do number of play
} // end of mega millions
private: System::Void groupBox1_Enter(System::Object^ sender, System::EventArgs^ e)
{
}
};
}
1>—— Build started: Project: Mega Millions 2 No data saving, Configuration: Debug Win32 ——
1>Compiling…
1>Mega Millions 2 No data saving.cpp
1>c:usersachongdocumentsvisual studio 2005projectsmega millions 2 no data savingmega millions 2 no data savingForm1.h(171) : error C2665: ‘System::Double::TryParse’ : none of the 3 overloads could convert all the argument types
1> c:windowsmicrosoft.netframeworkv2.0.50727mscorlib.dll: could be ‘bool System::Double::TryParse(System::String ^,double %)’
1> while trying to match the argument list ‘(System::String ^, short)’
1>c:usersachongdocumentsvisual studio 2005projectsmega millions 2 no data savingmega millions 2 no data savingForm1.h(224) : error C2061: syntax error : identifier ‘num3a’
1>c:usersachongdocumentsvisual studio 2005projectsmega millions 2 no data savingmega millions 2 no data savingForm1.h(231) : error C2061: syntax error : identifier ‘num4a’
1>c:usersachongdocumentsvisual studio 2005projectsmega millions 2 no data savingmega millions 2 no data savingForm1.h(238) : error C2061: syntax error : identifier ‘num5a’
1>c:usersachongdocumentsvisual studio 2005projectsmega millions 2 no data savingmega millions 2 no data savingForm1.h(245) : error C2061: syntax error : identifier ‘bonusnuma’
1>c:usersachongdocumentsvisual studio 2005projectsmega millions 2 no data savingmega millions 2 no data savingForm1.h(258) : error C2059: syntax error : ‘}’
Ok, I have it set up to use num1a to num5a. I declare them all, check the spelling. Used Int16. I checked everything. Why is it comming up with syntax error for no good reason. And the funny part is that num1a and num2a works fine
until it hits num3a. It just puts a number into the veriable and thats it. Whats with the syntax error when I used this before in my other programs.
MS Visual Studio version 8.0.50727.567 (vsvista.050727-8600)
Frame network Version 2.0.50727 sp
Ok, real simple. I declared all my veriable properly. I have tried this code before on another example. I am using academic edition just because I want to learn and try some programming stuff for fun. Then I hit this stupid brick
wall. Read Below.
Int16 upperlimitregular; // regular numbers
Int16 upperlimitbonus; // bonus numbers
Int16 bonusnuma;
Int16 num1a;
Int16 num2a;
Int16 num3a;
Int16 num4a;
Int16 num5a;
Int16 i;
#pragma endregion
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e)
{
num1a = 0;
num2a = 0;
num3a = 0;
num4a = 0;
num5a = 0;
// clear bonus number
bonusnuma = 0;
}
private: System::Void btnStart_Click(System::Object^ sender, System::EventArgs^ e)
{
// check numeric
//String^ strNumOfPlay;
Int16 dblNumOfPlay;
if(txtbxNumOfPlay->Text->Length > 0)
{
if(Double::TryParse(txtbxNumOfPlay->Text, dblNumOfPlay))
{
Int16 intNumOfPlay = dblNumOfPlay;
MegaMillion(intNumOfPlay);
}
else
{
txtbxResults->Text = «Number of plays must be numeric.»;
}// end if other then a number is inputted.
}// end if blank
else
{
txtbxResults->Text = «Please enter a number.»;
}// end if blank
}// end btnstart
private: Void MegaMillion(Int16 dblNumOfPlay)
{
DateTime moment = DateTime::Now;
Random^ randNumGen = gcnew Random(moment.Millisecond);
//
upperlimitregular = 56; // regular numbers
upperlimitbonus = 46;
//
// start do loop for 1 game, using the number of plays to stop the process.
// have to look up do loops again.
do while(i=0, i++, i=dblNumOfPlay)
{
// clear game for next game.
// clear array
num1a = 0;
num2a = 0;
num3a = 0;
num4a = 0;
num5a = 0;
// clear bonus number
bonusnuma = 0;
// get Randomize number
num1a = randNumGen->Next(upperlimitregular);
num1a += 1;
num2a = randNumGen->Next(upperlimitregular);
num2a += 1;
do while(num2a == num1a)
{
num2a = randNumGen->Next(upperlimitregular);
} // end number 2
num3a = randNumGen->Next(upperlimitregular);
num3a +=1;
do while(num3a == num1a || num3a == num2a)
{
num3a = randNumGen->Next(upperlimitregular);
}// end number 3
num4a = randNumGen->Next(upperlimitregular);
num4a += 1;
do while(num4a == num1a || num4a == num3a || num4a == num2a || num4a == num1a)
{
num4a = randNumGen->Next(upperlimitregular);
}// end number 4
num5a = randNumGen->Next(upperlimitregular);
num5a += 1;
do while(num5a == num4a || num5a == num3a || num5a == num2a || num5a == num1a)
{
num5a = randNumGen->Next(upperlimitregular);
}// end number 5
// Select 1 bonus number
bonusnuma = randNumGen->Next(upperlimitbonus);
bonusnuma +=1;
// Display results in result box
txtbxResults->Text = num1a.ToString(),» «, num2a.ToString(),» «,
num3a.ToString(),» «,num4a.ToString(),» «,
num5a.ToString(),» «,bonusnuma.ToString(), «/r/r/n»;
// Add numbers to database.
} // end do number of play
} // end of mega millions
private: System::Void groupBox1_Enter(System::Object^ sender, System::EventArgs^ e)
{
}
};
}
1>—— Build started: Project: Mega Millions 2 No data saving, Configuration: Debug Win32 ——
1>Compiling…
1>Mega Millions 2 No data saving.cpp
1>c:usersachongdocumentsvisual studio 2005projectsmega millions 2 no data savingmega millions 2 no data savingForm1.h(171) : error C2665: ‘System::Double::TryParse’ : none of the 3 overloads could convert all the argument types
1> c:windowsmicrosoft.netframeworkv2.0.50727mscorlib.dll: could be ‘bool System::Double::TryParse(System::String ^,double %)’
1> while trying to match the argument list ‘(System::String ^, short)’
1>c:usersachongdocumentsvisual studio 2005projectsmega millions 2 no data savingmega millions 2 no data savingForm1.h(224) : error C2061: syntax error : identifier ‘num3a’
1>c:usersachongdocumentsvisual studio 2005projectsmega millions 2 no data savingmega millions 2 no data savingForm1.h(231) : error C2061: syntax error : identifier ‘num4a’
1>c:usersachongdocumentsvisual studio 2005projectsmega millions 2 no data savingmega millions 2 no data savingForm1.h(238) : error C2061: syntax error : identifier ‘num5a’
1>c:usersachongdocumentsvisual studio 2005projectsmega millions 2 no data savingmega millions 2 no data savingForm1.h(245) : error C2061: syntax error : identifier ‘bonusnuma’
1>c:usersachongdocumentsvisual studio 2005projectsmega millions 2 no data savingmega millions 2 no data savingForm1.h(258) : error C2059: syntax error : ‘}’
Ok, I have it set up to use num1a to num5a. I declare them all, check the spelling. Used Int16. I checked everything. Why is it comming up with syntax error for no good reason. And the funny part is that num1a and num2a works fine
until it hits num3a. It just puts a number into the veriable and thats it. Whats with the syntax error when I used this before in my other programs.
MS Visual Studio version 8.0.50727.567 (vsvista.050727-8600)
Frame network Version 2.0.50727 sp
When I compile there is an error call «error C2061: syntax error : identifier ‘Player’ «
I can’t figure out what is wrong with my code. Here is my code
#include "Platform.h" #include "Player.h" class Collision { public: Collision(void); ~Collision(void); static bool IsCollision(Player &player, Platform& platform); };
There is an error in «IsCollision» method.
Player.h
#include <SFML/Graphics.hpp>
#include "rapidxml.hpp"
#include <fstream>
#include <iostream>
#include "Collision.h"
using namespace rapidxml;
class Player
{
private:
sf::Texture playerTexture;
sf::Sprite playerSprite;
sf::Vector2u position;
sf::Vector2u source;
sf::Vector2u size;
int frameCounter, switchFrame, frameSpeed;
int walkSpriteWidth;
float velocity;
bool isWalk;
bool isStand;
bool isFaceRight;
public:
Player(void);
~Player(void);
void Init();
void Draw(sf::RenderWindow *window);
void MoveForward();
void MoveBackward();
void Update(sf::Clock *clock);
void SetSourceY(int value);
void SetWalk(bool value);
void SetFacing(std::string value);
void SetStand(bool value);
void Stand();
std::string GetStatus();
void PrintStatus();
sf::Vector2f GetPosition();
int GetWidth();
int GetHeight();
};
georges619
2881 gold badge6 silver badges18 bronze badges
asked Apr 3, 2013 at 8:32
7
You have a circular include dependency. Collision.h includes Player.h and vice versa. The simplest solution is to remove #include "Collision.h"
from Player.h
, since the Collision
class is not needed in the Player
declaration. Besides that, it looks like some of your includes in Collision.h
can be replaced by forward declarations:
// forward declarations
class Player;
class Platform;
class Collision
{
public:
Collision(void);
~Collision(void);
static bool IsCollision(Player &player, Platform& platform);
};
You can then put the includes in Collision
‘s implementation file.
answered Apr 3, 2013 at 8:37
juanchopanzajuanchopanza
223k34 gold badges399 silver badges479 bronze badges
0
That’s a pretty common mistake — you have circular include dependency.
Looking at your code, you should replace #include "Player.h"
with class Player;
in Collision.h
. This is called «forward declaration» and will break the circular dependency.
Also, it would be good to add include guards, for example:
#ifndef MY_PLAYER_CLASS
#define MY_PLAYER_CLASS
...
#endif
And this should be done for each header you write.
answered Apr 3, 2013 at 8:37
Kiril KirovKiril Kirov
37.3k22 gold badges112 silver badges187 bronze badges
Circular dependency or you’re using a C compiler for C++ code
answered Apr 8, 2019 at 16:09
1
Timon32 0 / 0 / 0 Регистрация: 18.07.2015 Сообщений: 76 |
||||||||
1 |
||||||||
синтаксическая ошибка при определении функции шаблона02.12.2020, 19:10. Показов 2007. Ответов 8 Метки нет (Все метки)
Ошибка в определении Vector<T>::Iterator Vector<T>::Iterator::operator-(size_t i)const Вывод: .h
.inl
0 |
Комп_Оратор) 8863 / 4602 / 621 Регистрация: 04.12.2011 Сообщений: 13,740 Записей в блоге: 16 |
|
02.12.2020, 19:15 |
2 |
Timon32, вы разделили описание шаблона на 2 файла?
0 |
Timon32 0 / 0 / 0 Регистрация: 18.07.2015 Сообщений: 76 |
||||||||||||
02.12.2020, 20:21 [ТС] |
3 |
|||||||||||
Да. На данный момент мне удалось побороть ошибку, но не тем путем которым я хотел. На данный момент код выглядит так: .hpp:
.inl :
main:
0 |
Комп_Оратор) 8863 / 4602 / 621 Регистрация: 04.12.2011 Сообщений: 13,740 Записей в блоге: 16 |
|
02.12.2020, 21:01 |
4 |
но не тем путем которым я хотел. Но тем путём которым и следовало. Шаблон это не чертёж для построения исполнимого кода. Это чертёж для построения исходного кода. Компоновщик не может слинковать код который не сгенерирован. Всё нужно писать в заголовочник в итоге)
0 |
0 / 0 / 0 Регистрация: 18.07.2015 Сообщений: 76 |
|
02.12.2020, 21:57 [ТС] |
5 |
Не один раз видел как выносят реализацию шаблонных функций в отдельный файл(.inl).
0 |
Комп_Оратор) 8863 / 4602 / 621 Регистрация: 04.12.2011 Сообщений: 13,740 Записей в блоге: 16 |
|
02.12.2020, 22:51 |
6 |
Не один раз видел как выносят реализацию шаблонных функций в отдельный файл(.inl). Явные специализации — можно, сам шаблон — нет. Когда-то пытались это сделать (
0 |
0 / 0 / 0 Регистрация: 18.07.2015 Сообщений: 76 |
|
03.12.2020, 00:01 [ТС] |
7 |
0 |
Комп_Оратор) 8863 / 4602 / 621 Регистрация: 04.12.2011 Сообщений: 13,740 Записей в блоге: 16 |
|
03.12.2020, 00:23 |
8 |
Timon32, вы включаете файл в хедер. Я такого не видел и не имел ввиду. Тут скорее всего не идёт речь ни о какой раздельной компиляции. Потому что ваш ini файл не видит хедера и всё что в нём написано не будет распарсено компилятором в отдельной единице трансляции. Если ваш компилятор на стадии препроцессинга сразу сливает всё в один текст, то может оно и будет работать.
0 |
TheCalligrapher Вездепух 10968 / 5953 / 1628 Регистрация: 18.10.2014 Сообщений: 14,944 |
||||||||
03.12.2020, 00:47 |
9 |
|||||||
Сообщение было отмечено Timon32 как решение Решение
warning C4346: Iterator: зависимое имя не является типом Вам же сам компилятор ясно написал, что нужно сделать.
Что это вообще такое?
1 |
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();
};
Синтаксическая ошибка: идентификатор «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);
};