I’m having lots of errors in my final project (a poker and black jack sim). I’m using a vector to implement the «hands» in the blackJack class, and I’m using a structured data type declared in another class, which is publicly inherited. The error I’m worried about is the compiler I’m using telling me that I’m not declaring a type in the vector.
blackJack header file:
#ifndef BLACKJACK_H
#define BLACKJACK_H
#include <vector>
#include "card.h"
class blackJack: public cards
{
private:
vector <Acard> playerHand;
vector <Acard> dealerHand;
public:
blackJack();
void dealHands();
void hitOrStay();
void dealerHit();
int handleReward(int);
void printHands();
};
#endif
card header file (this is the class black jack inherits from):
#ifndef CARD_H
#define CARD_H
const char club[] = "xe2x99xa3";
const char heart[] = "xe2x99xa5";
const char spade[] = "xe2x99xa0";
const char diamond[] = "xe2x99xa6";
//structured data to hold card information
//including:
// a number, representing Ace-King (aces low)
//a character, representing the card's suit
struct Acard
{
int number;
char pic[4];
};
// a class to hold information regarding a deck of cards
//including:
//An array of 52 Acard datatypes, representing our Deck
//an index to the next card in the array
//a constructor initializing the array indices to Ace-king in each suit
//a function using random numbers to shuffle our deck of cards
//13 void functions to print each card
class cards
{
private:
Acard Deck[52];
int NextCard;
public:
cards();
Acard getCard();
void shuffleDeck();
void cardAce(char[]);
void cardTwo(char[]);
void cardThree(char[]);
void cardFour(char[]);
void cardFive(char[]);
void cardSix(char[]);
void cardSeven(char[]);
void cardEight(char[]);
void cardNine(char[]);
void cardTen(char[]);
void cardJack(char[]);
void cardQueen(char[]);
void cardKing(char[]);
};
#endif
i have this error in the title:
here class declaration of variables and prototypes of function
#ifndef ROZKLADLICZBY_H
#define ROZKLADLICZBY_H
class RozkladLiczby{
public:
RozkladLiczby(int); //konstruktor
vector<int> CzynnikiPierwsze(int); //metoda
~RozkladLiczby();
};
#endif
And class body:
#include "RozkladLiczby.h"
using namespace std;
#include <iostream>
#include <vector>
RozkladLiczby::~RozkladLiczby() //destruktor
{}
RozkladLiczby::RozkladLiczby(int n){
int* tab = new int[n+1];
int i,j;
for( i=0;i<=n;i++)
tab[i]=0; //zerujemy tablice
for( i=2;i<=n;i+=2)
tab[i]=2; //zajmujemy sie liczbami parzystymi
for(i=3; i<=n;i+=2)
for(j=i;j<=n;j+=i) //sito erastotesa
if(tab[j]==0)
tab[j]=i;
}
vector<int> RozkladLiczby::CzynnikiPierwsze(int m){
vector<int> tablica;
while(m!=1){
tablica.push_back(tab[m]);
m=m/tab[m];
}
return tablica;
}
Whats wrong with the prototype of function in first block? Why vector is told to be not a type? I would be grateful if u could help me to find out this.
asked Mar 22, 2014 at 12:25
Your header file does not include the vector header. Add a #include <vector>
to the beggining.
Besides, you should refer to it as std::vector<int>
instead of vector<int>
, since it belongs to the std
namespace. Declaring using namespace x;
in header files is not a good practice, as it will propagate to other files as well.
Shoe
74.6k35 gold badges165 silver badges269 bronze badges
answered Mar 22, 2014 at 12:31
0
Change your header file to:
#ifndef ROZKLADLICZBY_H
#define ROZKLADLICZBY_H
#include <vector>
class RozkladLiczby{
public:
RozkladLiczby(int); //konstruktor
std::vector<int> CzynnikiPierwsze(int); //metoda
~RozkladLiczby();
private:
int* tab;
};
#endif
answered Mar 22, 2014 at 12:29
πάντα ῥεῖπάντα ῥεῖ
86.9k13 gold badges114 silver badges189 bronze badges
8
0 / 0 / 0 Регистрация: 06.09.2017 Сообщений: 114 |
|
1 |
|
01.11.2017, 21:59. Показов 4998. Ответов 67
Доброго времени суток форумчане!
0 |
7534 / 6396 / 2917 Регистрация: 14.04.2014 Сообщений: 27,863 |
|
01.11.2017, 22:05 |
2 |
Ты заголовок подключил?
0 |
0 / 0 / 0 Регистрация: 06.09.2017 Сообщений: 114 |
|
01.11.2017, 22:10 [ТС] |
3 |
Какой заголовок? Заголовочный файл? Как эти файлы работают я не особо понимаю…
0 |
7534 / 6396 / 2917 Регистрация: 14.04.2014 Сообщений: 27,863 |
|
01.11.2017, 22:44 |
4 |
<vector> подключил?
0 |
0 / 0 / 0 Регистрация: 06.09.2017 Сообщений: 114 |
|
01.11.2017, 22:45 [ТС] |
5 |
да но не работает…
0 |
7534 / 6396 / 2917 Регистрация: 14.04.2014 Сообщений: 27,863 |
|
01.11.2017, 22:46 |
6 |
Показывай.
0 |
SkeiTax 0 / 0 / 0 Регистрация: 06.09.2017 Сообщений: 114 |
||||
01.11.2017, 22:49 [ТС] |
7 |
|||
Вот как я создаю вектор
вот что выводит компилятор «…|error: ‘vector’ does not name a type|» Добавлено через 1 минуту Это всё сообщение после сборки…
0 |
7534 / 6396 / 2917 Регистрация: 14.04.2014 Сообщений: 27,863 |
|
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 минуту
Когда пытаюсь обратиться из объекта класса Circle к этой функции выдаёт ошибку
0 |
7534 / 6396 / 2917 Регистрация: 14.04.2014 Сообщений: 27,863 |
|
01.11.2017, 22:56 |
10 |
Текст ошибки где?
0 |
SkeiTax 0 / 0 / 0 Регистрация: 06.09.2017 Сообщений: 114 |
||||||||||||
01.11.2017, 22:59 [ТС] |
11 |
|||||||||||
В главном методе создаю окно
Потом создаю объект одного из класса Circle/Circle2
В классе Circle я в методе Step() есть такое условие
и в итоге выдаёт ошибку: «…|error: cannot convert ‘sf::RenderWindow**’ to ‘sf::RenderWindow*’ for argument ‘2’ to ‘int mouse_xy(bool, sf::RenderWindow*)’|»
0 |
7534 / 6396 / 2917 Регистрация: 14.04.2014 Сообщений: 27,863 |
|
01.11.2017, 23:04 |
12 |
Тип второго параметра не верный. Может, там другой window?
0 |
SkeiTax 0 / 0 / 0 Регистрация: 06.09.2017 Сообщений: 114 |
||||
01.11.2017, 23:07 [ТС] |
13 |
|||
вот часть кода в Circle2
0 |
7534 / 6396 / 2917 Регистрация: 14.04.2014 Сообщений: 27,863 |
|
01.11.2017, 23:08 |
14 |
Ну так зачем ты двойной указатель передаёшь? Убери амперсанды.
0 |
SkeiTax 0 / 0 / 0 Регистрация: 06.09.2017 Сообщений: 114 |
||||
01.11.2017, 23:11 [ТС] |
15 |
|||
хорошо но тогда ошибка тоже… сейчас покажу Добавлено через 1 минуту Добавлено через 1 минуту
0 |
7534 / 6396 / 2917 Регистрация: 14.04.2014 Сообщений: 27,863 |
|
01.11.2017, 23:13 |
16 |
Там же всё написано. Redefenition — ты два раза одну и туже функцию описал, что ли?
0 |
SkeiTax 0 / 0 / 0 Регистрация: 06.09.2017 Сообщений: 114 |
||||
01.11.2017, 23:21 [ТС] |
17 |
|||
В смысле? Добавлено через 1 минуту
Добавлено через 3 минуты
0 |
7534 / 6396 / 2917 Регистрация: 14.04.2014 Сообщений: 27,863 |
|
01.11.2017, 23:22 |
18 |
0 |
SkeiTax 0 / 0 / 0 Регистрация: 06.09.2017 Сообщений: 114 |
||||||||||||
01.11.2017, 23:35 [ТС] |
19 |
|||||||||||
координату курсора мышки относительно окна window * Добавлено через 2 минуты Добавлено через 1 минуту
Все подключения в Circle2.cpp
И Include.h
Добавлено через 3 минуты Добавлено через 41 секунду Добавлено через 3 минуты
0 |
7534 / 6396 / 2917 Регистрация: 14.04.2014 Сообщений: 27,863 |
|
01.11.2017, 23:40 |
20 |
Если там указатели, просто delete и присваиваешь другой. От массива не отличается.
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
01.11.2017, 23:40 |
Помогаю со студенческими работами здесь Классы, объекты Классы и объекты КЛАССЫ И ОБЪЕКТЫ Рациональная (несократимая) дробь представляется парой целых чисел (а, b), где… Классы и объекты Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 20 |
C++ does not name a type error can occur due to multiple reasons like using an undefined class as a member, initializing the variables at wrong positions, etc. The earlier you figure out the issue, the sooner you’ll be able to fix it.
Hence, this post has been curated to let you know about the potential causes and provide you with the best fixing procedures. After reading this comprehensive guide, you’ll know what’s the next step to bring your program back from the trauma of the error.
Contents
- Which Reasons Can Cause C++ Does Not Name a Type Error?
- – Not Defining a Class Before Using It As a Member
- – Using a Class Reference or Pointer Even Before the Class Declaration
- – You Are Initializing the Variables at the Wrong Positions
- – The C++ Syntax Is Confusing for You
- – You Haven’t Specified the Namespace of the Class or Object
- How To Make the C++ Does Not Name a Type Error Fly Away?
- – Define the Class Before Using It As a Member
- – Leverage Forward Declaration
- – Define the Variables While Declaring Them
- – Define the Variables Inside a Function
- – Precede the Class Name With Its Namespace
- – Follow the C++ Syntax Correctly
- Conclusion
- References
Which Reasons Can Cause C++ Does Not Name a Type Error?
The C++ does not name a type error that occurs due to using an undefined class member, undeclared class pointer, or reference, or incorrectly defining the variables. Also, messing up the C++ syntax or using a class without specifying its namespace can put you in trouble and cause the same error.
Each problem is discussed below, along with an example to help you find the culprit in your program within minutes.
– Not Defining a Class Before Using It As a Member
If you use a class or struct as a member inside another class or struct before defining it, you’ll receive the struct does not name a type error. It would be beneficial to know that the compiler needs to calculate the size of a class or a struct when it is defined to know the space that the same class will occupy.
Now, if you add an undefined class member with an unknown size in another class, the compiler will throw an error. It indicates that the compiler isn’t able to calculate the class’s size. An example of this has been attached below:
{
public:
/* using a class member before defining it */
Petfood catFood;
};
class Petfood
{
public:
/* define the class here */
};
– Using a Class Reference or Pointer Even Before the Class Declaration
Although using a class reference or pointer before defining the same class is acceptable, you’ll get an error if the class isn’t even declared before it.
For example, you haven’t declared a class called “Books,” and you are using its reference in your “Shelf” class. In this case, the does not name a type C++ struct error will show up. Please look at the code below for clarification of the problem:
{
public:
void getBooks(Books& mybook);
};
– You Are Initializing the Variables at the Wrong Positions
Variable declaration and definition can be broken down into two steps. However, if you define a variable in a separate step and that step isn’t included inside a function body, you’ll be given an error.
Think about it this way: you have created a struct and declared two variables inside it. Next, you try to initialize the variables without wrapping them inside a function. In such a scenario, the “variable does not name a type – C++” error will appear on your screen. You can see the code block for the given scenario here:
{
int football;
int tennis;
};
Players currentPlayers;
currentPlayers.football = 5;
currentPlayers.tennis = 7;
– The C++ Syntax Is Confusing for You
Having confusion in the C++ syntax can lead you to make mistakes in your program and result in the stated error. The most common mistakes noticed in even the simple CPP files have been listed below:
- Missing, extra, or improperly placed semicolons and curly brackets.
- Function calls before the main() function.
- Not understanding the difference between various operators.
- Having numbers specified as strings to use them as integers.
– You Haven’t Specified the Namespace of the Class or Object
Having done everything right, if you are getting the same error, there might be a missing namespace. To understand it better, imagine that you are using the vector class present in the std namespace.
If you use the class without preceding it with its namespace and the double colon symbol “::,” the vector does not name a type error will be thrown during program compilation.
Similarly, if you use the cout object without a leading std namespace, the cout does not name a type in C++ will occur.
How To Make the C++ Does Not Name a Type Error Fly Away?
You can push away the C++ does not name a type error from your screen by being careful with class definitions, leveraging forward declaration, or defining the variables correctly. Moreover, following the C++ syntax correctly and preceding the class names with their namespaces can save your day.
You can read more about each solution below to identify and implement the best one immediately.
– Define the Class Before Using It As a Member
As you know that it’s crucial to define a class or struct before using it as a member inside another class or struct, so it would be better to implement it in your code. So, to remove the does not name a type C++ class error received in the previous example, you’ll have to swipe the positions of the Animals and Petfood classes.
Here you go with a working code snippet:
{
public:
/* define the class here */
};
class Animals
{
public:
Petfood catFood;
};
– Leverage Forward Declaration
The forward declaration can help you eliminate the error using an undefined class’s reference or pointer inside another class. The term refers to pre-defining or declaring a class to meet the flow of your program.
Continuing with the Books class example stated above, it would be better to forward declare it before using its reference in the Shelf class. Please refer to the following coding representation to leverage the forward declaration:
class Shelf
{
public:
void getBooks(Books& mybook);
};
– Define the Variables While Declaring Them
It would be best to define the variables while declaring them to avoid this error. So, for the struct example shared above, here is the code that won’t throw any errors:
{
int football = 5;
int tennis = 7;
};
However, if you aren’t willing to declare and define the variables in a single step, then go through the next solution.
– Define the Variables Inside a Function
Defining the variables inside a function will help you remove the x does not name a type Arduino error. Here, x refers to the name of your variable. Please feel free to use the below code block for error-free program compilation.
{
int football;
int tennis;
};
Players currentPlayers;
void myFunc(){
currentPlayers.football = 5;
currentPlayers.tennis = 7;
}
– Precede the Class Name With Its Namespace
It’s a good idea to precede the name of the class with its namespace and a double-colon “::” symbol to get rid of the given error. It will ensure that the compiler identifies the namespace of the class that you are using and compiles your code without falling for any confusion.
The given way to use a class is often considered better than adding a line like “using namespace xxx” in your file.
So, here you go with the correct way to use the vector class:
– Follow the C++ Syntax Correctly
Writing the correct C++ syntax can save you hours of finding the causes of different errors including the one discussed here and fixing them.
So, if you have tried all the solutions and nothing seems to work for you, double-check the syntax. Here are a few instructions that you can follow to have a clean and error-free code:
- Ensure that all statements end with a semicolon.
- Indent your code properly to stay right with the curly braces.
- Check and remove any function calls before the main() function.
- Specify the correct data types for your variables.
- Replace any inappropriate operators with the correct ones.
- If you doubt the correctness of some coding statements, accept guidance from Google to help you write them better.
Conclusion
The stack does not name a type error might pop up when your compiler is unable to understand your program. Therefore, the causes are often related to mistakes in the syntax or the declaration and definition of different classes, structs, or objects. Here are some statements to help you conclude the post better:
- Define the class prior to using it as a member in another class.
- Go for forward declaration for using class pointers and references.
- Define the variables inside a function or at the time of declaration.
- Precede the class names with their namespaces.
- Double-check your program’s syntax.
The more you take care of the details, the better you’ll be at avoiding the error.
References
- https://stackoverflow.com/questions/2133250/x-does-not-name-a-type-error-in-c
- https://www.codeproject.com/Questions/5265982/Why-does-Cplusplus-say-mynumber-does-not-name-a-ty
- https://forum.arduino.cc/t/compiler-error-does-not-name-a-type/517905/7
- https://discuss.codechef.com/t/does-not-name-a-type-error/96721
- https://stackoverflow.com/questions/8403468/error-vector-does-not-name-a-type
- https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice
- Author
- Recent Posts
Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team
- Forum
- Beginners
- vector does not name a type
vector does not name a type
Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team
- Forum
- Beginners
- vector does not name a type
vector does not name a type
I don’t why, but it doesn’t recognize neither vector nor string….I think I must have some wrong configuration in my settings project, but I don’t what it can be…does any one can help me?
|
|
Last edited on
Add on line 8:
|
|
that’s true they belong to the standard library…I guess I could insert too
Thanks, as my file was a simple .cpp I could use using directive but with more files, headers files and source files declare namespace explicitly in headers and use using directive in source files….thanks
Topic archived. No new replies allowed.