Error vector does not name a type

SFML. Вектора, массивы, классы, объекты C++ Решение и ответ на вопрос 2114656

0 / 0 / 0

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

Сообщений: 114

1

01.11.2017, 21:59. Показов 4741. Ответов 67


Доброго времени суток форумчане!
Возникла проблема с векторами. но понимаю как работают эти самые векторы.
Задача такова, есть абстрактный класс Object с какими-то функциями(это не столь важно). Так же есть дочерние классы такие как Circle и Circle2. В главной функции создаются новые объекты дочерних классов и заносятся в массив.
НО когда хочу сделать через вектор то выдаёт ошибку: «error: ‘vector’ does not name a type».
так же по мере решения это проблемы будет ещё несколько вопросов таких как: «Как реализовать уничтожение объектов Массива/Вектора», «Как сделать универсальную функцию определения координат курсора в окне»

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



0



7275 / 6220 / 2833

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

Сообщений: 26,871

01.11.2017, 22:05

2

Ты заголовок подключил?



0



0 / 0 / 0

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

Сообщений: 114

01.11.2017, 22:10

 [ТС]

3

Какой заголовок? Заголовочный файл? Как эти файлы работают я не особо понимаю…



0



7275 / 6220 / 2833

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

Сообщений: 26,871

01.11.2017, 22:44

4

<vector> подключил?



0



0 / 0 / 0

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

Сообщений: 114

01.11.2017, 22:45

 [ТС]

5

да но не работает…



0



7275 / 6220 / 2833

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

Сообщений: 26,871

01.11.2017, 22:46

6

Показывай.



0



SkeiTax

0 / 0 / 0

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

Сообщений: 114

01.11.2017, 22:49

 [ТС]

7

Вот как я создаю вектор

C++
1
vector<int> k(1);

вот что выводит компилятор «…|error: ‘vector’ does not name a type|»

Добавлено через 1 минуту
||=== Build file: «no target» in «no project» (compiler: unknown) ===|
|8|warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11|
|8|warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11|
|13|error: ‘vector’ does not name a type|
||=== Build failed: 1 error(s), 2 warning(s) (0 minute(s), 0 second(s)) ===|

Это всё сообщение после сборки…



0



7275 / 6220 / 2833

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

Сообщений: 26,871

01.11.2017, 22:49

8

std::vector сделай. Если не заработает, значит ты не подключил заголовок.



0



SkeiTax

0 / 0 / 0

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

Сообщений: 114

01.11.2017, 22:54

 [ТС]

9

Оп… Точно, чего-то не думал что в этом может быть проблема

Добавлено через 55 секунд
тогда следующий вопрос

Добавлено через 1 минуту
Вот часть кода в отдельном файле

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//Function.cpp
using namespace sf;
 
int mouse_xy(bool i, RenderWindow *win){
    int xy[2];
    Vector2i mouse_v;
 
    mouse_v = Mouse::getPosition(*win);
 
    xy[0] = mouse_v.x;
    xy[1] = mouse_v.y;
 
    return xy[i];
}
 
float distance_to_point(float x1, float y1, float x2, float y2){
    float x, y;
    x=pow(pow(x1-x2,2),0.5);
    y=pow(pow(y1-y2,2),0.5);
    return pow(x*x+y*y,0.5);
}

Когда пытаюсь обратиться из объекта класса Circle к этой функции выдаёт ошибку



0



7275 / 6220 / 2833

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

Сообщений: 26,871

01.11.2017, 22:56

10

Текст ошибки где?



0



SkeiTax

0 / 0 / 0

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

Сообщений: 114

01.11.2017, 22:59

 [ТС]

11

В главном методе создаю окно

C++
1
RenderWindow window(VideoMode(600, 500), "WinGraph");

Потом создаю объект одного из класса Circle/Circle2

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
if (!preSpase)
        if (Keyboard::isKeyPressed(Keyboard::Space)){
            Circle *cir = new Circle();
            cir->XX = mouse_xy(0, &window);
            cir->YY = mouse_xy(1, &window);
            cir->window = &window;
            cir->ID=id;
            cir->Create();
            obj[id] = cir;
            id++;
            upd=true;
        }
        if (!preControl)
        if (Keyboard::isKeyPressed(Keyboard::LControl)){
            Circle2 *cir = new Circle2();
            cir->XX = mouse_xy(0, &window);
            cir->YY = mouse_xy(1, &window);
            cir->window = &window;
            cir->ID=id;
            cir->Create();
            obj[id] = cir;
            id++;
            upd=true;
        }

В классе Circle я в методе Step() есть такое условие

C++
1
if (distance_to_point(x, y, mouse_xy(0,&window), mouse_xy(1,&window))<R);

и в итоге выдаёт ошибку: «…|error: cannot convert ‘sf::RenderWindow**’ to ‘sf::RenderWindow*’ for argument ‘2’ to ‘int mouse_xy(bool, sf::RenderWindow*)’|»



0



7275 / 6220 / 2833

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

Сообщений: 26,871

01.11.2017, 23:04

12

Тип второго параметра не верный. Может, там другой window?



0



SkeiTax

0 / 0 / 0

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

Сообщений: 114

01.11.2017, 23:07

 [ТС]

13

вот часть кода в Circle2

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
class Circle2 : public Object{
public:
    float x, XX, y, YY, speed, R=25;
    int dir, ID;
 
    RenderWindow *window;
    CircleShape shape;
 
    void Create(){
        x=XX;
        y=YY;
        dir=0;
        speed=0;
 
        shape.setRadius(R);
        shape.setOrigin(R,R);
        shape.setFillColor(Color(100,175,200));
    }
...
 
        if (speed<0) speed=0;
        if (Keyboard::isKeyPressed(Keyboard::A)) dir=180;
        if (Keyboard::isKeyPressed(Keyboard::D)) dir=0;
        if (Keyboard::isKeyPressed(Keyboard::W)) dir=90;
        if (Keyboard::isKeyPressed(Keyboard::S)) dir=270;
        y-=sin(dir*M_PI/180)*speed;
        x+=cos(dir*M_PI/180)*speed;
 
        if (distance_to_point(x, y, mouse_xy(0,&window), mouse_xy(1,&window))<R);
    }
 
    void Draw(){
        shape.setPosition(x, y);
        window->draw(shape);
    }



0



7275 / 6220 / 2833

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

Сообщений: 26,871

01.11.2017, 23:08

14

Ну так зачем ты двойной указатель передаёшь? Убери амперсанды.



0



SkeiTax

0 / 0 / 0

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

Сообщений: 114

01.11.2017, 23:11

 [ТС]

15

хорошо но тогда ошибка тоже… сейчас покажу

Добавлено через 1 минуту
||=== Build file: «no target» in «no project» (compiler: unknown) ===|
|8|warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11|
|8|warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11|
||In function ‘int mouse_xy(bool, sf::RenderWindow*)’:|
->|5|error: redefinition of ‘int mouse_xy(bool, sf::RenderWindow*)’|
|5|note: ‘int mouse_xy(bool, sf::RenderWindow*)’ previously defined here|
||In function ‘float distance_to_point(float, float, float, float)’:|
|17|error: redefinition of ‘float distance_to_point(float, float, float, float)’|
|17|note: ‘float distance_to_point(float, float, float, float)’ previously defined here|
||=== Build failed: 2 error(s), 2 warning(s) (0 minute(s), 0 second(s)) ===|

Добавлено через 1 минуту
в условии теперь без амперсантов

C++
1
if (distance_to_point(x, y, mouse_xy(0, window), mouse_xy(1, window))<R);



0



7275 / 6220 / 2833

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

Сообщений: 26,871

01.11.2017, 23:13

16

Там же всё написано. Redefenition — ты два раза одну и туже функцию описал, что ли?



0



SkeiTax

0 / 0 / 0

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

Сообщений: 114

01.11.2017, 23:21

 [ТС]

17

В смысле?

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

C++
1
if (distance_to_point(x, y, mouse_xy(0, window), mouse_xy(1, window))<R);

Добавлено через 3 минуты
функция возвращающая расстояние между точками — distance_to_point(x1, y1, x2, y2)
Возвращает координату по x и y если первый аргумент равен 0 или 1 соответственно — mouse_xy(0, window)



0



7275 / 6220 / 2833

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

Сообщений: 26,871

01.11.2017, 23:22

18



0



SkeiTax

0 / 0 / 0

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

Сообщений: 114

01.11.2017, 23:35

 [ТС]

19

координату курсора мышки относительно окна window *

Добавлено через 2 минуты
В файле Cickle2.cpp подключается <Function.cpp> и в Main.cpp

Добавлено через 1 минуту
Все подключения в Main.cpp

C++
1
2
3
4
5
6
#include "Include.h"
#include "Object.cpp"
#include "Circle1.cpp"
#include "Circle2.cpp"
#include "Function.cpp"
#include <vector>

Все подключения в Circle2.cpp

C++
1
2
#include "Include.h"
#include "Function.cpp"

И Include.h

C++
1
2
3
4
5
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/System/Vector2.hpp>
#include <math.h>

Добавлено через 3 минуты
Благодарю за помощь я понял в чём была беда)

Добавлено через 41 секунду
Теперь меня интересует ещё кое что

Добавлено через 3 минуты
Вот у меня есть объект Circle & Circle2. В данный момент они сохраняются в массив Object *obj[1];
я хочу передать под вектор всё это дело и как я понимаю это выглядит так: vector<Object*> obj;
И вот как например удалять созданные объекты которые «сохраняются» в этот вектор и как и него добавлять новые объекты Circle и Circle2?



0



7275 / 6220 / 2833

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

Сообщений: 26,871

01.11.2017, 23:40

20

Если там указатели, просто delete и присваиваешь другой. От массива не отличается.



0



IT_Exp

Эксперт

87844 / 49110 / 22898

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

Сообщений: 92,604

01.11.2017, 23:40

Помогаю со студенческими работами здесь

Классы, объекты
Привет. Необходимо обратиться к объекту не используя (например, TextBox a = (TextBox)sender) т.к….

Классы и объекты
Создать объявление класса и разработать программу-драйвер, который продемонстрирует работу класса….

КЛАССЫ И ОБЪЕКТЫ
Помогите с кодом:

Рациональная (несократимая) дробь представляется парой целых чисел (а, b), где…

Классы и объекты
Здравствуйте объясните пожалуйста следующую задачу
Нужно создать класс данных А и класс…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

20

Я довольно новичок в C ++, & У меня проблема с объявлением векторов в качестве переменной класса. Я заставил их работать в другом месте моего кода, используя похожую стратегию, но мне не нравится мой заголовочный файл.

error: ‘vector’ does not name a type
error: ‘vector’ has not been declared
error: expected ‘,’ or ‘...’ before ‘<’ token
error: ‘vector’ does not name a type

Я прокомментировал строки, которые GCC указывает на проблему.

#ifndef HEADER_H
#define HEADER_H

#include <cstdlib>
#include <vector>
#include <string>

using std::string;

//  Class declarations

class Node {
int id;
string type;
public:
Node(int, string);
int get_id();
string get_type();
string print();
};

class Event {
string name, date, time;
public:
Event(string, string, string);
string get_name();
string get_date();
string get_time();
string print();
};

class Course {
char id;
std::vector<Node*> nodes[40];     // This one
public:
Course(char, std::vector<Node*>); // This one
char get_id();
std::vector<Node*> get_nodes();   // & this one.
string print();
};class Entrant {
int id;
Course* course;
string name;
public:
Entrant(int, char, string);
int get_id();
Course* get_course();
string get_name();
string print();
};

//  Function declarations

void menu_main();

void nodes_load();
void event_create();
void entrant_create();
void course_create();#endif  /* HEADER_H */

Вот скриншот ошибки в моей IDE, если это дает больше подсказок.

0

Решение

Единственная проблема, с которой я столкнулся при компиляции вашего кода, это то, что вы используете Course в Entrant класс, но у вас нет определения для Course в таком случае.

Если вы перешлите объявить Course чуть выше Entrant вот так:

class Course;

class Entrant { }; //class definition

Затем ваш код компилируется, в соответствии с этим живой пример

3

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

Ты обманываешь 😉 . Код, который вы дали нам, имеет std::vector, который работает, в то время как код на вашем скриншоте имеет vector который не работает (компилятор не знает, где его взять).

Решение: измените код для использования std::vector,

3

C++ has many orthogonal ways of preventing you from doing what you asked for. When I’m doing
training courses, I often find students confused (without necessarily knowing they’re confused)
between these various failure modes. So I thought I’d write down the most common ones in a blog post.

You can’t modify it because it’s const

void read_it(int);
void write_it(int&);

struct S {
    int m;
    void foo() const;
};

void S::foo() const {
    m = 42;  // ERROR: can't modify a const object
}

const S s = {42};
read_it(s.m);
write_it(s.m);  // ERROR: call would lose const qualifier

For more on this subject, see “const is a contract” (2019-01-03).

You can’t name it because it’s inaccessible

class C {
public:
    int pub;
    int *getpriv() { return &priv; }
private:
    int priv;
};

C c;
read_it(c.pub);
write_it(c.pub);
read_it(c.priv);   // ERROR: inaccessible
write_it(c.priv);  // ERROR: inaccessible

In this case, the problem is that the member priv is private — it’s not accessible in contexts that
aren’t either members or friends of class C. The compiler is basically saying that you can’t name c.priv.

You can’t use the name of c.priv, but you can still modify the object denoted by c.priv, if you can
get a reference to it by some other approach. For example, the class can expose a public API getpriv() that
returns a pointer to the private data member.

read_it(*c.getpriv());  // OK
write_it(*c.getpriv());  // OK

Access control affects your ability to name the private member, regardless of what you’re
planning to do with it. If it’s inaccessible, you can’t read it or write it.

int i = f();      // ERROR: 'f' was not declared in this scope
C *c;             // ERROR: 'C' does not name a type
std::set<int> s;  // ERROR: no template named 'set' in namespace std
boost::regex rx;  // ERROR: 'boost' does not name a type; did you mean 'bool'?

In C++, everything you use — functions, variables, types, type aliases, namespaces — must be declared
before use. Without a declaration telling it that C is a class type, or that std::set is a class template,
the compiler cannot figure out how to use those names at all.

So, you have to #include <vector> before you try to use std::vector.

The standard library has no particular organizing principle — it evolved over decades — so some of
its header names are hard to remember. You have to #include <algorithm>
before you use (some overloads of) std::swap. You have to #include <memory> before you use
std::unique_ptr.

Starting in GCC 9, GCC will no longer attempt to “auto-correct” the identifiers boost
and bsl
to bool. Prior to GCC 9, if you see an error message ending in “…did you mean bool?”, it’s
a sure bet that you forgot to include some library header.

Its real name is more qualified than what you wrote

#include <vector>

vector<int> v;  // ERROR: 'vector' does not name a type

Remember, C++ doesn’t have “modules” or “packages” in the Python or Java sense. We have headers and
we have namespaces, and they are orthogonal. Using #include <vector> to bring the declaration of
std::vector into scope does not entitle you to refer to that type as simply vector.

A using-declaration can provide a shorter name for a previously declared type — but, vice versa,
a using-declaration alone does not cause the original declaration to become visible.

using std::vector;  // ERROR: 'vector' has not been declared
vector<int> v;

You need to #include the proper header first; then you can use using to create shorter synonyms
if you want. (But, generally speaking, you should not want.)

The linker can’t find its implementation

main.o: In function `main':
main.cpp:4: undefined reference to `foo()'
collect2: error: ld returned 1 exit status

Even if you’ve included the right headers, using’ed the right namespaces, qualified all your names correctly,
and the compiler is happy, you might find that the linker is unhappy with your program. This is often because
one of your .cpp files calls a function which is declared, but never defined. Maybe it’s defined
in libfoo.a, but you forgot to pass -lfoo to the linker. Maybe it’s defined in foo.o, but you forgot to
add foo.cpp to your project. Maybe you legitimately forgot to write its definition anywhere.

Two special cases to be aware of:

The undefined entity is a static const data member

Static data members are just global variables with funky names;
they must be defined somewhere out-of-line. Static const data members are schizophrenic: for many purposes they
behave like constexpr compile-time constants, but if you ever take the address of a static const data member
(even by taking a reference to it), then you’ll need an out-of-line definition again. Example:

void byvalue(int);
void byref(const int&);

struct S {
    static constexpr int one = 1;
    static const int two = 2;
    void foo();
};

void S::foo() {
    byvalue(one);  // OK
    byvalue(two);  // OK
    byref(one);    // OK
    byref(two);    // LINKER ERROR: `two` is undefined
}

Add an out-of-line definition to one of your .cpp files — or, better, use static constexpr int instead.
In C++17, constexpr static data members don’t need out-of-line definitions.
(In C++17 and later, you could even use static inline const int; but I see no advantage to static inline const
over static constexpr.)

For more on this subject, see “Why do I get a linker error with static const and value_or?” (2020-09-19).

The undefined entity is a vtable

If you see an undefined reference to “vtable for SomeClass,” like this:

main.o: In function `main':
main.cpp:4: undefined reference to `vtable for Foo'
collect2: error: ld returned 1 exit status

then you might wonder how you’d ever provide an out-of-line definition for the vtable. That’s the compiler’s
responsibility, isn’t it? Well, according to
the most common ABI for C++,
the compiler always emits the vtable in the same .o file as the definition of the first virtual member function
of the class. (Not counting inline functions and pure virtuals, of course.) So if you see this kind of error,
you should act as if the linker were complaining about the first virtual function in the offending class.
Did you implement it? Did you link that .cpp file into your project?

For non-virtual member functions, it’s normally perfectly fine to declare member functions that you never define;
but for virtual member functions, you must provide a definition for every declaration — no exceptions!

Понравилась статья? Поделить с друзьями:
  • Error vds basic provider
  • Error vdisk s offline see msa storage virtual disk overview panel
  • Error vcruntime140 dll
  • Error vbox base path contains invalid characters
  • Error vbnc30203 identifier expected