Error c2061 синтаксическая ошибка идентификатор noexcept

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
Если прописать определение в объявлении, то ошибки не будет.

Вывод:
warning C4346: Iterator: зависимое имя не является типом
message : укажите префикс «typename» для задания типа
error C2061: синтаксическая ошибка: идентификатор «Iterator»
error C2143: синтаксическая ошибка: отсутствие «;» перед «{«
error C2447: {: отсутствует заголовок функции (возможно, используется формальный список старого типа)

.h

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Iterator
        {
        public:
            Iterator();
            Iterator(const Vector& r);
            Iterator(const Iterator& r) = default;
 
            Iterator& operator=(const Iterator& r) = default;
            Iterator& operator++();  //prefix
            Iterator operator++(int);//postfix
            Iterator operator+(size_t i)const;
            Iterator operator-(size_t i)const;
            T& operator*()const;
 
            friend Vector;
        private:
            Vector* v;
            size_t i;
        };

.inl

C++
1
2
3
4
5
6
7
8
9
10
11
template<typename T>
    Vector<T>::Iterator Vector<T>::Iterator::operator-(size_t i)const
    {
        auto t = *this;
        t.i -= i;
    }
    template<typename T>
    inline T& Vector<T>::Iterator::operator*() const
    {
        return v[i];
    }

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

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 вызывал подобные ошибки.
Среда разработки vs19.

На данный момент код выглядит так:

.hpp:

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
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
#pragma once #include <utility>   namespace IP {     template <typename T>     class Vector     {     public:         class Iterator         {         public:             Iterator();             Iterator(Vector& r);             Iterator(const Iterator& r) = default;               Iterator& operator=(const Iterator& r) = default;             Iterator& operator++() { ++i; return *this;};  //prefix             Iterator operator++(int) { auto t = *this;++i;return t; };//postfix             Iterator operator+(size_t i)const { auto t = *this; t.i += i; };             Iterator operator-(size_t i)const { auto t = *this; t.i -= i; };             bool operator==(const Iterator& r);             bool operator!=(const Iterator& r);             T& operator*()const;               friend Vector;         private:             Vector* v;             size_t i;         };           class ConstIterator         {         public:             ConstIterator();             ConstIterator(const Vector& r);             ConstIterator(const ConstIterator& r) = default;               ConstIterator& operator=(const ConstIterator& r) = default;             ConstIterator& operator++() { ++i; return *this; };  //prefix             ConstIterator operator++(int) { auto t = *this; ++i; return t; };//postfix             ConstIterator operator+(size_t i)const { auto t = *this; t.i += i; };             ConstIterator operator-(size_t i)const { auto t = *this; t.i -= i; };             bool operator==(const ConstIterator& r);             bool operator!=(const ConstIterator& r);             const T& operator*()const;               friend Vector;         private:             const Vector* v;             size_t i;         };           Vector();         Vector(const Vector& r);         Vector(Vector&& r) noexcept;         ~Vector();           void pushBack(const T& el);         template <typename ...Args>         void emplaceBack(Args&&... args);         void reserve(size_t new_capasity);         void erase(size_t begin, size_t end);         void clear();         size_t getSize() const;           Vector& operator=(const Vector& r);           Iterator begin(){ return Iterator(*this); };         Iterator end(){Iterator i; i.i = size; i.v = this; return i;};           ConstIterator begin()const { return ConstIterator(*this); };         ConstIterator end()const { ConstIterator i; i.i = size; i.v = this; return i; };           ConstIterator cbegin()const { return ConstIterator(*this); };         ConstIterator cend()const { ConstIterator i; i.i = size; i.v = this; return i; }           T& operator[](size_t i);         const T& operator[](size_t i) const;       private:         T* data;         size_t size;         size_t capasity;     }; }   #include "vector.inl"

.inl :

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 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 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 
#include "vector.hpp" //#include "vector.hpp" #pragma once   namespace IP {     //---Iterator---//     template<typename T>     inline Vector<T>::Iterator::Iterator(): v(nullptr), i(0) {}     template<typename T>     inline Vector<T>::Iterator::Iterator(Vector& r) : v(&r), i(0) {}         //template<typename T>     //inline Vector<T>::Iterator& Vector<T>::Iterator::operator++()  //prefix     //{     //  ++i;     //  return *this;     //}     /*template<typename T>     Vector<T>::Iterator inline Vector<T>::Iterator::operator++(int)//postfix     {         auto t = *this;         ++i;         return t;     }*/     /*template<typename T>     Vector<T>::Iterator Vector<T>::Iterator::operator+(size_t i)const     {         auto t = *this;         t.i += i;     }*/     /*template<typename T>     Vector<T>::Iterator          Vector<T>::Iterator::operator-(size_t i)const     {         auto t = *this;         t.i -= i;     }*/     template<typename T>     bool Vector<T>::Iterator::operator==(const Iterator& r)     {         return v == r.v && i == r.i;     }     template<typename T>     bool Vector<T>::Iterator::operator!=(const Iterator& r)     {         return v != r.v || i != r.i;     }     template<typename T>     inline T& Vector<T>::Iterator::operator*() const     {         return v->operator[](i);     }     //---iterator---//         //---ConstIterator---//     template<typename T>     inline Vector<T>::ConstIterator::ConstIterator() :v(nullptr), i(0) {}     template<typename T>     Vector<T>::ConstIterator::ConstIterator(const Vector& r) : v(&r), i(0) {}     //template<typename T>     //inline Vector<T>::ConstIterator& Vector<T>::ConstIterator::operator++()  //prefix     //{     //  ++i;     //  return *this;     //}     //template<typename T>     //Vector<T>::ConstIterator inline Vector<T>::ConstIterator::operator++(int)//postfix     //{     //  auto t = *this;     //  ++i;     //  return t;     //}     //template<typename T>     //Vector<T>::ConstIterator Vector<T>::ConstIterator::operator+(size_t i)const     //{     //  auto t = *this;     //  t.i += i;     //}     //template<typename T>     //Vector<T>::ConstIterator Vector<T>::ConstIterator::operator-(size_t i)const     //{     //  auto t = *this;     //  t.i -= i;     //}     template<typename T>     bool Vector<T>::ConstIterator::operator==(const ConstIterator& r)     {         return v == r.v && i == r.i;     }     template<typename T>     bool Vector<T>::ConstIterator::operator!=(const ConstIterator& r)     {         return v != r.v || i != r.i;     }     template<typename T>     inline const T& Vector<T>::ConstIterator::operator*() const     {         return v->operator[](i);     }     //---iterator---//         //---vector---//     template<typename T>     inline Vector<T>::Vector():         data(static_cast<T*>(operator new[](10 * sizeof(T)))), size(0), capasity(10)     {}     template<typename T>     inline Vector<T>::Vector(const Vector& r):         data(static_cast<T*>(operator new[](r.size * sizeof(T)))), size(r.size), capasity(r.size)     {         for (size_t i = 0; i < size; i++)             new (data + i) T(r.data[i]);     }     template<typename T>     inline Vector<T>::Vector(Vector&& r) noexcept:         data(r.data), size(r.size), capasity(r.capasity)     {         r.data = nullptr;     }     template<typename T>     inline Vector<T>::~Vector()     {         if (data == nullptr)             return;           for (size_t i = 0; i < size; i++)             data[i].~T();           operator delete[](data);     }       template<typename T>     void inline Vector<T>::pushBack(const T& el)     {         if (size == capasity)             reserve(size * 2);           new (data + size) T(el);           size++;     }     template<typename T>     template<typename ...Args>     void inline Vector<T>::emplaceBack(Args&&... args)     {         if (size == capasity)             reserve(size * 2);           new (data + size) T(std::move(args ...));           size++;     }     template<typename T>     void inline Vector<T>::reserve(size_t new_capasity)     {         if (this->size >= size)             return;           T* temp_data = static_cast<T*>(operator new[](new_capasity * sizeof(T)));           for (size_t i = 0; i < size; i++)             new (temp_data + i) T(std::move(data[i]));           for (size_t i = 0; i < size; i++)             data[i].~T();           operator delete[](data);           data = temp_data;         capasity = new_capasity;     }     template<typename T>     void inline Vector<T>::erase(size_t begin, size_t end)     {         for (size_t i = begin; i != end; i++)             data[i].~T();           size -= end - begin;         for (size_t i = begin; i < size; i++)         {             new (data + i) T(std::move(data[i + end - begin]));             data[i + end - begin].~T();         }     }     template<typename T>     void inline Vector<T>::clear()     {         for (size_t i = 0; i < size; i++)             data[i].~T();         size = 0;     }     template<typename T>     inline size_t Vector<T>::getSize() const     {         return size;     }       template<typename T>     Vector<T>& Vector<T>::operator=(const Vector& r)     {         for (size_t i = 0; i < size; i++)             data[i].~T();           if (capasity < r.size)         {             operator delete[](data);             data = static_cast<T*>(operator new[](r.size * sizeof(T)));             capasity = r.size;         }           size = r.size;         for (size_t i = 0; i < size; i++)             new (data + i) T(r.data[i]);           return *this;     }       /*template<typename T>     Vector<T>::Iterator Vector<T>::begin()     {         return Iterator(*this);     }     template<typename T>     Vector<T>::Iterator Vector<T>::end()     {         Iterator i;         i.i = size;         v = *this;         return i;     }*/       template<typename T>     T& Vector<T>::operator[](size_t i)     {         return data[i];     }     template<typename T>     const T& Vector<T>::operator[](size_t i) const     {         return data[i];     }     //---vector---// }

main:

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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 
#include <iostream> #include "vector.hpp"   using namespace std;   using IP::Vector;   class Test { public:     //Test():a(0) { cout << "defoult" << endl; }     Test(size_t a):a(a) { cout << "param" << endl; }     Test(const Test& r):a(r.a) { cout << "copy" << endl; }     Test(Test&& r)noexcept :a(r.a) { cout << "move" << endl; }     ~Test() { cout << "del" << endl; }     size_t a; };   int main() {     Vector<Test> v;       v.pushBack(0);     v.pushBack(1);     v.pushBack(2);     v.pushBack(3);     v.emplaceBack(Test(4));       for (size_t i = 0; i < v.getSize(); i++)     {         cout << v[i].a << endl;     }     cout << endl;     v.erase(0, 2);       const Vector<Test> v2(v);     for (const auto& t : v2)     {         cout << t.a << endl;     }     cout << endl;       Vector<Test> v3;     v3.emplaceBack(100);     v3.emplaceBack(100);     v3.emplaceBack(100);       v3 = v2;     for (const auto& t : v3)     {         cout << t.a << endl;     } }

0

Комп_Оратор)

Эксперт по математике/физике

8771 / 4510 / 608

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

Сообщений: 13,454

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

02.12.2020, 21:01

4

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

но не тем путем которым я хотел.

Но тем путём которым и следовало. Шаблон это не чертёж для построения исполнимого кода. Это чертёж для построения исходного кода. Компоновщик не может слинковать код который не сгенерирован. Всё нужно писать в заголовочник в итоге)

0

0 / 0 / 0

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

Сообщений: 76

02.12.2020, 21:57

 [ТС]

5

Не один раз видел как выносят реализацию шаблонных функций в отдельный файл(.inl).
Да и писать код так проще.
Как было сказано ранее, компилируются все функции кроме тех которые пытаются возвращать Vector<T>::Iterator & Vector<T>::ConstIterator. Мне интересно почему?

0

Комп_Оратор)

Эксперт по математике/физике

8771 / 4510 / 608

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

Сообщений: 13,454

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

02.12.2020, 22:51

6

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

Не один раз видел как выносят реализацию шаблонных функций в отдельный файл(.inl).

Явные специализации — можно, сам шаблон — нет. Когда-то пытались это сделать (export), но передумали .

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

Вездепух

Эксперт CЭксперт С++

10420 / 5692 / 1550

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

Сообщений: 14,018

03.12.2020, 00:47

9

Лучший ответ Сообщение было отмечено Timon32 как решение

Решение

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

warning C4346: Iterator: зависимое имя не является типом
message : укажите префикс «typename» для задания типа

Вам же сам компилятор ясно написал, что нужно сделать.

C++
1 2 3 4 5 6 
template<typename T>     typename Vector<T>::Iterator Vector<T>::Iterator::operator-(size_t i)const     {         auto t = *this;         t.i -= i;     }

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

C++
1 
friend Vector;

Что это вообще такое?

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's user avatar

georges619

2881 gold badge7 silver badges18 bronze badges

asked Apr 3, 2013 at 8:32

aratn0n's user avatar

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

juanchopanza's user avatar

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 Kirov's user avatar

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

Stocazzo's user avatar

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 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 …

Jump to Post

This might be basic, but have you included UI.h in the current file?

Jump to Post

All 5 Replies

Member Avatar

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; } 

Member Avatar

10 Years Ago

It is public. Any other ideas?

Thank you for taking an interest, by the way.

Member Avatar

10 Years Ago

This might be basic, but have you included UI.h in the current file?

Member Avatar

10 Years Ago

It turns out I had a circular dependency with my headers. Thank you for helping though!

Member Avatar


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's user avatar

georges619

2881 gold badge6 silver badges18 bronze badges

asked Apr 3, 2013 at 8:32

aratn0n's user avatar

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

juanchopanza's user avatar

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 Kirov's user avatar

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

Stocazzo's user avatar

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
Если прописать определение в объявлении, то ошибки не будет.

Вывод:
warning C4346: Iterator: зависимое имя не является типом
message : укажите префикс «typename» для задания типа
error C2061: синтаксическая ошибка: идентификатор «Iterator»
error C2143: синтаксическая ошибка: отсутствие «;» перед «{«
error C2447: {: отсутствует заголовок функции (возможно, используется формальный список старого типа)

.h

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Iterator
        {
        public:
            Iterator();
            Iterator(const Vector& r);
            Iterator(const Iterator& r) = default;
 
            Iterator& operator=(const Iterator& r) = default;
            Iterator& operator++();  //prefix
            Iterator operator++(int);//postfix
            Iterator operator+(size_t i)const;
            Iterator operator-(size_t i)const;
            T& operator*()const;
 
            friend Vector;
        private:
            Vector* v;
            size_t i;
        };

.inl

C++
1
2
3
4
5
6
7
8
9
10
11
template<typename T>
    Vector<T>::Iterator Vector<T>::Iterator::operator-(size_t i)const
    {
        auto t = *this;
        t.i -= i;
    }
    template<typename T>
    inline T& Vector<T>::Iterator::operator*() const
    {
        return v[i];
    }



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 вызывал подобные ошибки.
Среда разработки vs19.

На данный момент код выглядит так:

.hpp:

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
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
#pragma once
#include <utility>
 
namespace IP
{
    template <typename T>
    class Vector
    {
    public:
        class Iterator
        {
        public:
            Iterator();
            Iterator(Vector& r);
            Iterator(const Iterator& r) = default;
 
            Iterator& operator=(const Iterator& r) = default;
            Iterator& operator++() { ++i; return *this;};  //prefix
            Iterator operator++(int) { auto t = *this;++i;return t; };//postfix
            Iterator operator+(size_t i)const { auto t = *this; t.i += i; };
            Iterator operator-(size_t i)const { auto t = *this; t.i -= i; };
            bool operator==(const Iterator& r);
            bool operator!=(const Iterator& r);
            T& operator*()const;
 
            friend Vector;
        private:
            Vector* v;
            size_t i;
        };
 
        class ConstIterator
        {
        public:
            ConstIterator();
            ConstIterator(const Vector& r);
            ConstIterator(const ConstIterator& r) = default;
 
            ConstIterator& operator=(const ConstIterator& r) = default;
            ConstIterator& operator++() { ++i; return *this; };  //prefix
            ConstIterator operator++(int) { auto t = *this; ++i; return t; };//postfix
            ConstIterator operator+(size_t i)const { auto t = *this; t.i += i; };
            ConstIterator operator-(size_t i)const { auto t = *this; t.i -= i; };
            bool operator==(const ConstIterator& r);
            bool operator!=(const ConstIterator& r);
            const T& operator*()const;
 
            friend Vector;
        private:
            const Vector* v;
            size_t i;
        };
 
        Vector();
        Vector(const Vector& r);
        Vector(Vector&& r) noexcept;
        ~Vector();
 
        void pushBack(const T& el);
        template <typename ...Args>
        void emplaceBack(Args&&... args);
        void reserve(size_t new_capasity);
        void erase(size_t begin, size_t end);
        void clear();
        size_t getSize() const;
 
        Vector& operator=(const Vector& r);
 
        Iterator begin(){ return Iterator(*this); };
        Iterator end(){Iterator i; i.i = size; i.v = this; return i;};
 
        ConstIterator begin()const { return ConstIterator(*this); };
        ConstIterator end()const { ConstIterator i; i.i = size; i.v = this; return i; };
 
        ConstIterator cbegin()const { return ConstIterator(*this); };
        ConstIterator cend()const { ConstIterator i; i.i = size; i.v = this; return i; }
 
        T& operator[](size_t i);
        const T& operator[](size_t i) const;
 
    private:
        T* data;
        size_t size;
        size_t capasity;
    };
}
 
#include "vector.inl"

.inl :

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
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
#include "vector.hpp"
//#include "vector.hpp"
#pragma once
 
namespace IP
{
    //---Iterator---//
    template<typename T>
    inline Vector<T>::Iterator::Iterator(): v(nullptr), i(0) {}
    template<typename T>
    inline Vector<T>::Iterator::Iterator(Vector& r) : v(&r), i(0) {}
    
    //template<typename T>
    //inline Vector<T>::Iterator& Vector<T>::Iterator::operator++()  //prefix
    //{
    //  ++i;
    //  return *this;
    //}
    /*template<typename T>
    Vector<T>::Iterator inline Vector<T>::Iterator::operator++(int)//postfix
    {
        auto t = *this;
        ++i;
        return t;
    }*/
    /*template<typename T>
    Vector<T>::Iterator Vector<T>::Iterator::operator+(size_t i)const
    {
        auto t = *this;
        t.i += i;
    }*/
    /*template<typename T>
    Vector<T>::Iterator 
        Vector<T>::Iterator::operator-(size_t i)const
    {
        auto t = *this;
        t.i -= i;
    }*/
    template<typename T>
    bool Vector<T>::Iterator::operator==(const Iterator& r)
    {
        return v == r.v && i == r.i;
    }
    template<typename T>
    bool Vector<T>::Iterator::operator!=(const Iterator& r)
    {
        return v != r.v || i != r.i;
    }
    template<typename T>
    inline T& Vector<T>::Iterator::operator*() const
    {
        return v->operator[](i);
    }
    //---iterator---//
 
 
    //---ConstIterator---//
    template<typename T>
    inline Vector<T>::ConstIterator::ConstIterator() :v(nullptr), i(0) {}
    template<typename T>
    Vector<T>::ConstIterator::ConstIterator(const Vector& r) : v(&r), i(0) {}
    //template<typename T>
    //inline Vector<T>::ConstIterator& Vector<T>::ConstIterator::operator++()  //prefix
    //{
    //  ++i;
    //  return *this;
    //}
    //template<typename T>
    //Vector<T>::ConstIterator inline Vector<T>::ConstIterator::operator++(int)//postfix
    //{
    //  auto t = *this;
    //  ++i;
    //  return t;
    //}
    //template<typename T>
    //Vector<T>::ConstIterator Vector<T>::ConstIterator::operator+(size_t i)const
    //{
    //  auto t = *this;
    //  t.i += i;
    //}
    //template<typename T>
    //Vector<T>::ConstIterator Vector<T>::ConstIterator::operator-(size_t i)const
    //{
    //  auto t = *this;
    //  t.i -= i;
    //}
    template<typename T>
    bool Vector<T>::ConstIterator::operator==(const ConstIterator& r)
    {
        return v == r.v && i == r.i;
    }
    template<typename T>
    bool Vector<T>::ConstIterator::operator!=(const ConstIterator& r)
    {
        return v != r.v || i != r.i;
    }
    template<typename T>
    inline const T& Vector<T>::ConstIterator::operator*() const
    {
        return v->operator[](i);
    }
    //---iterator---//
 
 
    //---vector---//
    template<typename T>
    inline Vector<T>::Vector():
        data(static_cast<T*>(operator new[](10 * sizeof(T)))), size(0), capasity(10)
    {}
    template<typename T>
    inline Vector<T>::Vector(const Vector& r):
        data(static_cast<T*>(operator new[](r.size * sizeof(T)))), size(r.size), capasity(r.size)
    {
        for (size_t i = 0; i < size; i++)
            new (data + i) T(r.data[i]);
    }
    template<typename T>
    inline Vector<T>::Vector(Vector&& r) noexcept:
        data(r.data), size(r.size), capasity(r.capasity)
    {
        r.data = nullptr;
    }
    template<typename T>
    inline Vector<T>::~Vector()
    {
        if (data == nullptr)
            return;
 
        for (size_t i = 0; i < size; i++)
            data[i].~T();
 
        operator delete[](data);
    }
 
    template<typename T>
    void inline Vector<T>::pushBack(const T& el)
    {
        if (size == capasity)
            reserve(size * 2);
 
        new (data + size) T(el);
 
        size++;
    }
    template<typename T>
    template<typename ...Args>
    void inline Vector<T>::emplaceBack(Args&&... args)
    {
        if (size == capasity)
            reserve(size * 2);
 
        new (data + size) T(std::move(args ...));
 
        size++;
    }
    template<typename T>
    void inline Vector<T>::reserve(size_t new_capasity)
    {
        if (this->size >= size)
            return;
 
        T* temp_data = static_cast<T*>(operator new[](new_capasity * sizeof(T)));
 
        for (size_t i = 0; i < size; i++)
            new (temp_data + i) T(std::move(data[i]));
 
        for (size_t i = 0; i < size; i++)
            data[i].~T();
 
        operator delete[](data);
 
        data = temp_data;
        capasity = new_capasity;
    }
    template<typename T>
    void inline Vector<T>::erase(size_t begin, size_t end)
    {
        for (size_t i = begin; i != end; i++)
            data[i].~T();
 
        size -= end - begin;
        for (size_t i = begin; i < size; i++)
        {
            new (data + i) T(std::move(data[i + end - begin]));
            data[i + end - begin].~T();
        }
    }
    template<typename T>
    void inline Vector<T>::clear()
    {
        for (size_t i = 0; i < size; i++)
            data[i].~T();
        size = 0;
    }
    template<typename T>
    inline size_t Vector<T>::getSize() const
    {
        return size;
    }
 
    template<typename T>
    Vector<T>& Vector<T>::operator=(const Vector& r)
    {
        for (size_t i = 0; i < size; i++)
            data[i].~T();
 
        if (capasity < r.size)
        {
            operator delete[](data);
            data = static_cast<T*>(operator new[](r.size * sizeof(T)));
            capasity = r.size;
        }
 
        size = r.size;
        for (size_t i = 0; i < size; i++)
            new (data + i) T(r.data[i]);
 
        return *this;
    }
 
    /*template<typename T>
    Vector<T>::Iterator Vector<T>::begin()
    {
        return Iterator(*this);
    }
    template<typename T>
    Vector<T>::Iterator Vector<T>::end()
    {
        Iterator i;
        i.i = size;
        v = *this;
        return i;
    }*/
 
    template<typename T>
    T& Vector<T>::operator[](size_t i)
    {
        return data[i];
    }
    template<typename T>
    const T& Vector<T>::operator[](size_t i) const
    {
        return data[i];
    }
    //---vector---//
}

main:

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include "vector.hpp"
 
using namespace std;
 
using IP::Vector;
 
class Test
{
public:
    //Test():a(0) { cout << "defoult" << endl; }
    Test(size_t a):a(a) { cout << "param" << endl; }
    Test(const Test& r):a(r.a) { cout << "copy" << endl; }
    Test(Test&& r)noexcept :a(r.a) { cout << "move" << endl; }
    ~Test() { cout << "del" << endl; }
    size_t a;
};
 
int main()
{
    Vector<Test> v;
 
    v.pushBack(0);
    v.pushBack(1);
    v.pushBack(2);
    v.pushBack(3);
    v.emplaceBack(Test(4));
 
    for (size_t i = 0; i < v.getSize(); i++)
    {
        cout << v[i].a << endl;
    }
    cout << endl;
    v.erase(0, 2);
 
    const Vector<Test> v2(v);
    for (const auto& t : v2)
    {
        cout << t.a << endl;
    }
    cout << endl;
 
    Vector<Test> v3;
    v3.emplaceBack(100);
    v3.emplaceBack(100);
    v3.emplaceBack(100);
 
    v3 = v2;
    for (const auto& t : v3)
    {
        cout << t.a << endl;
    }
}



0



Комп_Оратор)

Эксперт по математике/физике

8863 / 4602 / 621

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

Сообщений: 13,740

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

02.12.2020, 21:01

4

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

но не тем путем которым я хотел.

Но тем путём которым и следовало. Шаблон это не чертёж для построения исполнимого кода. Это чертёж для построения исходного кода. Компоновщик не может слинковать код который не сгенерирован. Всё нужно писать в заголовочник в итоге)



0



0 / 0 / 0

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

Сообщений: 76

02.12.2020, 21:57

 [ТС]

5

Не один раз видел как выносят реализацию шаблонных функций в отдельный файл(.inl).
Да и писать код так проще.
Как было сказано ранее, компилируются все функции кроме тех которые пытаются возвращать Vector<T>::Iterator & Vector<T>::ConstIterator. Мне интересно почему?



0



Комп_Оратор)

Эксперт по математике/физике

8863 / 4602 / 621

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

Сообщений: 13,740

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

02.12.2020, 22:51

6

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

Не один раз видел как выносят реализацию шаблонных функций в отдельный файл(.inl).

Явные специализации — можно, сам шаблон — нет. Когда-то пытались это сделать (export), но передумали .



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

Вездепух

Эксперт CЭксперт С++

10968 / 5953 / 1628

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

Сообщений: 14,944

03.12.2020, 00:47

9

Лучший ответ Сообщение было отмечено Timon32 как решение

Решение

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

warning C4346: Iterator: зависимое имя не является типом
message : укажите префикс «typename» для задания типа

Вам же сам компилятор ясно написал, что нужно сделать.

C++
1
2
3
4
5
6
template<typename T>
    typename Vector<T>::Iterator Vector<T>::Iterator::operator-(size_t i)const
    {
        auto t = *this;
        t.i -= i;
    }

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

C++
1
friend Vector;

Что это вообще такое?



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);
};

  • Error at loading of ippcv library photoshop 2021 решение ошибки
  • Error archive data corrupted unarc dll вернул код ошибки 5 не хватает памяти
  • Error 999999 ошибка выполнения функции arcgis
  • Error 80004005 неопознанная ошибка elsa
  • Error 601 battery как убрать ошибку