Меню

Ошибка vector does not name a type

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

user3402584's user avatar

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

Shoe

74k34 gold badges166 silver badges268 bronze badges

answered Mar 22, 2014 at 12:31

mateusazis's user avatar

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

πάντα ῥεῖ's user avatar

πάντα ῥεῖπάντα ῥεῖ

86.3k13 gold badges112 silver badges186 bronze badges

9

  • 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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

#include <stdio.h>
#include <string>
#include <tuple>
#include <iostream>
#include <vector>


struct Assoc{
	vector<pair<string,int>> vec;
	
	const int& operator[] (const string&) const;
	int& operator[](const string&);
};



int main(){
	
}

Last edited on

Add on line 8:

1
2
3
using std::vector;
using std::string;
using std::pair;

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.

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!

У меня много ошибок в моем финальном проекте (симулятор покера и блэкджека). Я использую вектор для реализации «рук» в классе блэкджека, и я использую структурированный тип данных, объявленный в другом классе, который публично наследуется. Ошибка, о которой я беспокоюсь, заключается в том, что компилятор, который я использую, говорит мне, что я не объявляю тип в векторе.

Заголовочный файл блэкджека:

 #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 

файл заголовка карты (это класс, от которого наследуется блэкджек):

 #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

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка video tdr failure nvlddmkm sys windows 10
  • Ошибка vds40 gta 4