Error count does not name a type

I was learning Adam Drozdek's book "Data Structures and Algorithms in C++", well, I typed the code in page 15 in my vim and compiled it in terminal of my Ubuntu 11.10. #include #i...

I was learning Adam Drozdek’s book «Data Structures and Algorithms in C++», well, I typed the code in page 15 in my vim and compiled it in terminal of my Ubuntu 11.10.

#include <iostream>
#include <cstring>
using namespace std;

struct Node{
    char *name;
    int age;
    Node(char *n = "", int a = 0){
        name = new char[strlen(n) + 1];
        strcpy(name, n);
        age = a;
    }
};

Node node1("Roger", 20), node2(node1);
cout << node1.name << ' ' << node1.age << ' ' << node2.name << ' ' << node2.age;
strcpy(node2.name, "Wendy");
node2.name = 30;
cout << node1.name << ' ' << node1.age << ' ' << node2.name << ' ' << node2.age;

But there’s some error:

oo@oo:~$ g++ unproper.cpp -o unproper
unproper.cpp:15:23: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
unproper.cpp:16:1: error: ‘cout’ does not name a type
unproper.cpp:17:7: error: expected constructor, destructor, or type conversion before ‘(’ token
unproper.cpp:18:1: error: ‘node2’ does not name a type
unproper.cpp:19:1: error: ‘cout’ does not name a type

I have searched this,this,this and this, but I can’t find the answer.

Any help would be appreciated:)

Error does not name a type in C++

The «error does not name a type» in C/C++ is defined as the when user declares outside of the function or does not include it properly in the main file this error will through.

TABLE OF CONTENTS
  1. Why this error occurs?
  2. How to resolve:
    1. Solution 1:
    2. Solution 2:
    3. Solution 3:
  3. Conclusion

Why this error occurs?

File: sample.h  
 #ifndef SAMPLE_H__<br />#define SAMPLE_H__
   namespace Sampletest {
    class CP_M_ReferenceCounted<br />{<br />};
    }
    #endif
    <br />File : test.cpp
#include "sample.h"
    typedef CP_M_ReferenceCounted FxRC;
   <br />int main(int argc, char **argv)<br />{
    <p>return 0;<br />}

If you run the above code you will get the error «…error: CP_M_ReferenceCounted does not name a type»

How to resolve :

To overcome this error follow this two methods of solutions

Solution 1:

To avoid this error, we have to add the «using namespace Sampletest» at the start of the program in C++.

To avoid this error, we have to add the «using namespace Sampletest» at the start of the program in C++.

<p>File : test.cpp</p>
<p><code>#include "sample.h"</p>
<p>//Add the following to your code</p>
<p>using namespace Sampletest</p>
<p>typedef CP_M_ReferenceCounted FxRC;</p>
<p><br />int main(int argc, char **argv)<br />{</p>
<p>return 0;<br />}</code></p>

Solution 2:

To avoid this kind of error we need to add the header «#include sample.h» at the starting of the program in C++.

Same Problem while declaring outside of the function

These kinds of errors are also acquired while printing outside of any function.
A statement which isn’t declaration in C++ need to be printed inside of the function

File test.cpp

<p>#include <iostream><br />#include <cstring><br />using namespace std;</p>
<p>struct Node{<br />char *name;<br />int age;<br />Node(char *nc = "", int ax = 0){<br />name = new char[strlen(nc) + 1];<br />strcpy(name, n);<br />age = ax;<br />}<br />};</p>
<p>Node node1("Roger", 20), node2(node1);<br />cout << node1.name << ' ' << node1.age << ' ' << node2.name << ' ' << node2.age;<br />strcpy(node2.name, "Wendy");<br />node2.name = 30;<br />cout << node1.name << ' ' << node1.age << ' ' << node2.name << ' ' << node2.age;</p>
<p> </p>
<p><b>Output :</b></p>
<p>error: ‘node2’ does not name a type</p>
<br/>

Solution 3:

To avoid these types of errors you need to add everything inside the function,
because a statement that isn’t a declaration in C++ needs to be inside the function

<p><code>int main() {<br />Node node1("Roger", 20), node2(node1);<br />cout << node1.name << ' ' << node1.age << ' ' << node2.name << ' ' << node2.age;<br />strcpy(node2.name, "Wendy");<br />node2.name = 30;<br />cout << node1.name << ' ' << node1.age << ' ' << node2.name << ' ' << node2.age;<br />}</code></p>

Conclusion:

In this article, we have seen why the undefined error occurs in C/C++ and discussed how to resolve these errors in various methods.

Dancing_god

15 / 2 / 1

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

Сообщений: 227

1

17.12.2020, 01:23. Показов 10745. Ответов 14

Метки c++ (Все метки)


Здравствуйте. Пишу программу на С++, реализующую структуру данных множество в виде класса.

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
#include <iostream>
#include <cstdlib>
 
using namespace std;
 
class MySet{
    private:
        // мощность универсума и счетчик множеств
        static int N, cnt;
        // мощность множества
        int n;
        // тег и значение машинного слова для множества
        char S, *A;
    public:
        // перегрузка оператора присвоения объединения
        MySet& operator |= (const MySet&);
        // перегрузка оператора присвоения объединения
        MySet operator | (const MySet&) const;
        // перегрузка оператора присвоения пересечения
        MySet& operator &= (const MySet&);
        // перегрузка оператора пересечения
        MySet operator & (const MySet&) const;
        // дополнение до универсума
        MySet operator ~() const;
        // вывод множества на дисплей
        void Show();
        // получение мощности множества
        int power() {return n;};
        // конструктор множества
        MySet(char);
// конструктор множества по умолчанию
        MySet();
        // конструктор копии
        MySet(const MySet&);
        // оператор присваивания
        MySet& MySet operator = (const MySet&);
        // деструктор
        ~MySet() {delete [] A;};
};
 
// методы класса MySet
// операция присваивания объединения множеств
MySet& MySet::operator |= (const MySet& rightSet){
    for(int i = 0; i < rightSet.n; ++i){
        for(int j = 0; j < n; ++j){
            if(rightSet.A[i] != A[j]){
                A[n++] = rightSet.A[i];
                break;
            }
        }
    }
    A[n] = 0;
    return *this;
}
 
// операция объединения множеств
MySet MySet::operator | (const MySet& rightSet) const{
    MySet leftSet(*this);
    return (leftSet |= rightSet);
}
 
// операция присваивания пересечения множеств
MySet& MySet::operator &= (const MySet& rightSet){
    MySet leftSet(*this);
    n = 0;
    for(int i = 0; i < leftSet.n; ++i){
        for(int j = 0; j < rightSet.n; ++j){
            if(leftSet.A[i] == rightSet.A[j]){
                A[n++] = leftSet.A[i];
                break;
            }
        }
    }
    return *this;
}
 
// операция пересечения множеств
MySet MySet::operator & (const MySet& rightSet) const{
    MySet leftSet(*this);
    return (leftSet &= rightSet);
}
 
// операция дополнения до универсума
MySet MySet::operator ~() const{
    MySet C();
    for(int i = 0; i < 10; ++i){
        bool condition = true;
        for(int j = 0; j < n; ++j){
            if(A[j]==i){
condition = false;
                break;
            }
        }
        if(condition){
            C.A[C.n++] = i;
        }
    }
    return C;
}
 
// функция показа множества на экране
void MySet::Show (){
    cout<<'n'<<S<<"=["<<A<<"]";
}
 
// конструктор
MySet::MySet(): n(0), S('A'+cnt++), A(new char[N+1]){
    A[0] = 0;
}
 
// конструктор случайного множества
MySet::MySet(char): n(0), S('A'+cnt++), A(new char[N+1]){
    for(int i = 0; i < N; i++){
        if(rand()%2){
            A[n++] = '0'+i;
        }
    }
    A[n] = 0;
cout<<'n'<<S<<"=["<<A<<"]";
}
 
// конструктор копирования
MySet::MySet(const MySet& B): n(B.n), S('A'+cnt++), A(new char[N+1]){
    // инициализация адресов/счетчиков
    char *dst(A), *src(B.A);
    // копирование символов до обнаружения 0
    while(*dst++ = *src++);
}
 
// перегрузка присваивания
MySet& MySet::operator = (const MySet& B){
    if(this != &B){
        char *dst(A), *src(B.A);
        n = B.n;
        while(*dst++ = *src++);
        S = 'A' + cnt++;
    }
    return *this;

Собственно при компиляции gcc выдает:

Код

MySet does not name a type.

Что означает, понятно. Но почему компилятор не видит прототип класса, объявленный в начале файла?

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



0



DrOffset

16495 / 8988 / 2205

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

Сообщений: 15,611

17.12.2020, 01:33

2

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

MySet C();

C++
1
MySet C;

Добавлено через 2 минуты
Выше — это определенно ошибка, но может быть не единственная.
Строку, в которой выдается эта ошибка, покажете?
И это ведь, очевидно, не все, что участвует в компиляции. Вы уверены, что проблема именно в этом файле?



0



15 / 2 / 1

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

Сообщений: 227

17.12.2020, 01:40

 [ТС]

3

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

Выше — это определенно ошибка, но может быть не единственная.

Это попытка исправить ошибку в данной строке. И по незнанию, тоже ошибка.
Вывод большой:

Код

array.cpp:37:16: error: expected ‘;’ at end of member declaration
         MySet& MySet operator = (const MySet&);
                ^~~~~
array.cpp:37:40: error: ‘MySet’ does not name a type
         MySet& MySet operator = (const MySet&);
                                        ^~~~~
array.cpp:37:46: error: ISO C++ forbids declaration of ‘operator=’ with no type [-fpermissive]
         MySet& MySet operator = (const MySet&);
                                              ^
array.cpp:37:16: error: field ‘MySet& MySet::MySet’ with same name as class [-fpermissive]
         MySet& MySet operator = (const MySet&);
                ^~~~~
array.cpp:44:34: error: ‘MySet’ does not name a type
 MySet& MySet::operator |= (const MySet& rightSet){
                                  ^~~~~
array.cpp:44:8: error: prototype for ‘MySet& MySet::operator|=(const int&)’ does not match any in class ‘MySet’
 MySet& MySet::operator |= (const MySet& rightSet){
        ^~~~~
array.cpp:17:16: error: candidate is: MySet& MySet::operator|=(const MySet&)
         MySet& operator |= (const MySet&);
                ^~~~~~~~
array.cpp:58:32: error: ‘MySet’ does not name a type
 MySet MySet::operator | (const MySet& rightSet) const{
                                ^~~~~
array.cpp:58:7: error: prototype for ‘MySet MySet::operator|(const int&) const’ does not match any in class ‘MySet’
 MySet MySet::operator | (const MySet& rightSet) const{
       ^~~~~
array.cpp:19:15: error: candidate is: MySet MySet::operator|(const MySet&) const
         MySet operator | (const MySet&) const;
array.cpp:64:34: error: ‘MySet’ does not name a type
 MySet& MySet::operator &= (const MySet& rightSet){
                                  ^~~~~
array.cpp:64:8: error: prototype for ‘MySet& MySet::operator&=(const int&)’ does not match any in class ‘MySet’
 MySet& MySet::operator &= (const MySet& rightSet){
        ^~~~~
array.cpp:21:16: error: candidate is: MySet& MySet::operator&=(const MySet&)
         MySet& operator &= (const MySet&);
                ^~~~~~~~
array.cpp:79:32: error: ‘MySet’ does not name a type
 MySet MySet::operator & (const MySet& rightSet) const{
                                ^~~~~
array.cpp:79:7: error: prototype for ‘MySet MySet::operator&(const int&) const’ does not match any in class ‘MySet’
 MySet MySet::operator & (const MySet& rightSet) const{
       ^~~~~
array.cpp:23:15: error: candidate is: MySet MySet::operator&(const MySet&) const
         MySet operator & (const MySet&) const;
               ^~~~~~~~
array.cpp: In member function ‘MySet MySet::operator~() const’:
array.cpp:86:11: error: expected ‘;’ before ‘C’
     MySet C();
           ^
array.cpp:96:13: error: ‘C’ was not declared in this scope
             C.A[C.n++] = i;
             ^
array.cpp:99:12: error: ‘C’ was not declared in this scope
     return C;
            ^
array.cpp: In constructor ‘MySet::MySet()’:
array.cpp:108:1: error: uninitialized reference member in ‘class MySet&’ [-fpermissive]
 MySet::MySet(): n(0), S('A'+cnt++), A(new char[N+1]){
array.cpp:37:16: note: ‘MySet& MySet::MySet’ should be initialized
         MySet& MySet operator = (const MySet&);
                ^~~~~
array.cpp: In constructor ‘MySet::MySet(char)’:
array.cpp:113:1: error: uninitialized reference member in ‘class MySet&’ [-fpermissive]
 MySet::MySet(char): n(0), S('A'+cnt++), A(new char[N+1]){
 ^~~~~
array.cpp:37:16: note: ‘MySet& MySet::MySet’ should be initialized
         MySet& MySet operator = (const MySet&);
                ^~~~~
array.cpp: At global scope:
array.cpp:125:20: error: ‘MySet’ does not name a type
 MySet::MySet(const MySet& B): n(B.n), S('A'+cnt++), A(new char[N+1]){
                    ^~~~~
array.cpp:125:1: error: prototype for ‘MySet::MySet(const int&)’ does not match any in class ‘MySet’
 MySet::MySet(const MySet& B): n(B.n), S('A'+cnt++), A(new char[N+1]){
 ^~~~~
array.cpp:35:9: error: candidates are: MySet::MySet(const MySet&)
         MySet(const MySet&);
         ^~~~~
array.cpp:108:1: error:                 MySet::MySet()
 MySet::MySet(): n(0), S('A'+cnt++), A(new char[N+1]){
 ^~~~~
array.cpp:113:1: error:                 MySet::MySet(char)
 MySet::MySet(char): n(0), S('A'+cnt++), A(new char[N+1]){
 ^~~~~
array.cpp:133:33: error: ‘MySet’ does not name a type
 MySet& MySet::operator = (const MySet& B){
                                 ^~~~~
array.cpp:133:8: error: prototype for ‘MySet& MySet::operator=(const int&)’ does not match any in class ‘MySet’
 MySet& MySet::operator = (const MySet& B){
array.cpp:7:7: error: candidates are: MySet& MySet::operator=(const MySet&)
 class MySet{
       ^~~~~
array.cpp:37:22: error:                 int MySet::operator=(const int&)
         MySet& MySet operator = (const MySet&);

компилирую только данный файл. В начале думал, что проблема с заголовочным файлом. Вынес прототип класса в исполняемый файл .cpp (в вышеприведенный).
Собственно все ошибки — из того факта, что компилятор не считает MySet за тип данных, то есть почему-то не находит объявление класса.



0



hoggy

Эксперт С++

8719 / 4299 / 958

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

Сообщений: 9,744

17.12.2020, 01:41

4

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

Но почему компилятор не видит прототип класса, объявленный в начале файла?

вот это что такое?

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

MySet& MySet operator = (const MySet&);

а вот это что такое?

C++
1
MySet C();

это — объявление прототипа функции, если ты вдруг не понял.

одно неправильное объявление провоцирует другие ошибки:

Код

error: request for member ‘A’ in ‘C’, which is of non-class type ‘MySet()’
             C.A[C.n++] = i;
               ^

и вот таких мелких косяков у тебя в коде:

Код

Error(s):
1151805807/source.cpp: In member function ‘MySet MySet::operator~() const’:
1151805807/source.cpp:80:15: error: request for member ‘A’ in ‘C’, which is of non-class type ‘MySet()’
             C.A[C.n++] = i;
               ^
1151805807/source.cpp:80:19: error: request for member ‘n’ in ‘C’, which is of non-class type ‘MySet()’
             C.A[C.n++] = i;
                   ^
1151805807/source.cpp:83:12: error: invalid conversion from ‘MySet (*)()’ to ‘char’ [-fpermissive]
     return C;
            ^
1151805807/source.cpp:19:9: note:   initializing argument 1 of ‘MySet::MySet(char)’
         MySet(char);
         ^~~~~
1151805807/source.cpp: In constructor ‘MySet::MySet()’:
1151805807/source.cpp:92:28: warning: conversion to ‘char’ from ‘int’ may alter its value [-Wconversion]
 MySet::MySet(): n(0), S('A'+cnt++), A(new char[N+1]){
                         ~~~^~~~~~
1151805807/source.cpp: In constructor ‘MySet::MySet(char)’:
1151805807/source.cpp:97:32: warning: conversion to ‘char’ from ‘int’ may alter its value [-Wconversion]
 MySet::MySet(char): n(0), S('A'+cnt++), A(new char[N+1]){
                             ~~~^~~~~~
1151805807/source.cpp:100:25: warning: conversion to ‘char’ from ‘int’ may alter its value [-Wconversion]
             A[n++] = '0'+i;
                      ~~~^~
1151805807/source.cpp: In copy constructor ‘MySet::MySet(const MySet&)’:
1151805807/source.cpp:108:44: warning: conversion to ‘char’ from ‘int’ may alter its value [-Wconversion]
 MySet::MySet(const MySet& B): n(B.n), S('A'+cnt++), A(new char[N+1]){
                                         ~~~^~~~~~
1151805807/source.cpp:112:18: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
     while(*dst++ = *src++);
           ~~~~~~~^~~~~~~~
1151805807/source.cpp: In member function ‘MySet& MySet::operator=(const MySet&)’:
1151805807/source.cpp:120:22: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
         while(*dst++ = *src++);
               ~~~~~~~^~~~~~~~
1151805807/source.cpp:121:17: warning: conversion to ‘char’ from ‘int’ may alter its value [-Wconversion]
         S = 'A' + cnt++;
             ~~~~^~~~~~~



1



16495 / 8988 / 2205

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

Сообщений: 15,611

17.12.2020, 01:44

5

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

Решение

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

array.cpp:37:16: error: expected ‘;’ at end of member declaration
MySet& MySet operator = (const MySet&);

Прочитайте внимательно текст ошибки.



1



15 / 2 / 1

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

Сообщений: 227

17.12.2020, 01:47

 [ТС]

6

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

это — объявление прототипа функции, если ты вдруг не понял.

Я не спорю, что это ошибка. И сейчас, да, понимаю, что прототип функции. Исправление этой ошибки все же не решило главной проблемы.



0



16495 / 8988 / 2205

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

Сообщений: 15,611

17.12.2020, 01:48

7

Dancing_god, обычно в диагностике компилятора существует только одна ошибка, которую вы и должны устранять — она самая первая в списке. На остальное можно не обращать внимания до тех пор, пока вы не устраните первую. В данном случае у вас лишний MySet после MySet&, видимо оставленный по невнимательности. Все остальные ошибки, скорее всего, спровоцированы этой, первой.



1



15 / 2 / 1

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

Сообщений: 227

17.12.2020, 01:51

 [ТС]

8

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

Прочитайте внимательно текст ошибки.

Да, прочитал. Действительно глупая ошибка. Спасибо за помощь.

Добавлено через 27 секунд

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

спровоцированы этой, первой.

Именно так.



0



KZProg

0 / 0 / 0

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

Сообщений: 51

07.09.2021, 18:02

9

У меня ошибка: ‘S’ does not name a type. Вот текст программы — по вычислению площади замкнутой области методом трапеций:

C
1
2
3
4
5
float S, x, h = 0.001;
S = (f1(x1) - f2(x1) + f1(x2) - f2(x2)) / 2.;
for ( x = x1+h; x <= x2-h; x += h )
  S += f1(x) - f2(x);
S *= h;

. Помогите!



0



Вездепух

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

10435 / 5704 / 1553

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

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

07.09.2021, 18:23

10

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

Вот текст программы — по вычислению площади замкнутой области методом трапеций:

Это не «текст программы». Это огрызок текста программы, по котрому ничего сказать нельзя. В какой строке ошибка?



0



0 / 0 / 0

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

Сообщений: 51

07.09.2021, 18:47

11

Во второй.



0



Вездепух

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

10435 / 5704 / 1553

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

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

07.09.2021, 20:21

12

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

Во второй.

Вы что-то выдумываете. Приводите реальный текст программы.



0



2057 / 1615 / 532

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

Сообщений: 6,080

07.09.2021, 22:31

14

KZProg, и где f1, f2 и x1, x2.
Вы собрали код с примеров ? Где он ?



0



Вездепух

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

10435 / 5704 / 1553

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

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

07.09.2021, 22:34

15

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

В том-то как раз и дело, что текст приводится так, как есть в источнике.

А, ну то есть вы совершенно не понимаете, что делаете.

Если вы действительно читали источник, то вам должно быть понятно, что это никакая не «программа», а лишь фрагмент программы. Пытаться компилировать вот этот фрагмент как «программу» совершенно бесполезно.

Ваш источник обладает относительно низким качеством изложения, но как должна выглядеть программа на языке С там более-менее объяснено. (Также, в вашем источнике идет речь о языке С. Почему вы постите это все в форум по языку С++?)



1



IT_Exp

Эксперт

87844 / 49110 / 22898

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

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

07.09.2021, 22:34

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

Ошибка Record, object or class type required
unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,…

[Ошибка] : Record, object or class type required
Выдает ошибку:

Unit_Kartka.pas(134): Record, object or class type required

Ошибка: Record, object or class type required
Код программы:
unit UnitZakazch;

interface

uses
Winapi.Windows, Winapi.Messages,…

Ошибка type qualifier ‘std’ must be a struct or class name
а у меня на эту строку typedef std::string T_str; выдается ошибка type qualifier ‘std’ must be a…

Ошибка: record, object or class type required
Вод полный код окна Form1:
unit Unit1;

interface

uses
Windows, Messages, SysUtils,…

Ошибка: Record object or class type required
{$WARN SYMBOL_PLATFORM OFF}
unit FormMain;

interface

uses
Windows, Messages, SysUtils,…

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

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

15

  • Forum
  • Beginners
  • does not name a type error

does not name a type error

Hi, Code::Blocks keeps giving me this error message whenever I try to compile:

‘LinkListIterator’ does not name a type

I’ve checked for spelling errors in my preprocessor identifiers and header files, and made sure to include the appropriate header files in the implementation files. But Im stumped and have no idea how to fix this. Any assistance will be appreciated. Thanks.

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
// UnorderedLinkList.h

# ifndef H_UnorderedLinkList
# define H_UnorderedLinkList

# include "LinkListIterator.h"

struct NodeType
{
    int info;
    NodeType *link;
};

class UnorderedLinkList
{
    public:        
        LinkListIterator begin();
        LinkListIterator end();
        UnorderedLinkList();        

    protected:
        int count;
        NodeType *first;
        NodeType *last;
};

# endif 
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
// UnorderedLinkList.cpp

# include "UnorderedLinkList.h"
# include <iostream>
using namespace std;

LinkListIterator UnorderedLinkList::begin()
{
    LinkListIterator temp(first);

    return temp;
}


LinkListIterator UnorderedLinkList::end()
{
    LinkListIterator temp(NULL);

    return temp;
}

UnorderedLinkList::UnorderedLinkList()
{
    first = NULL;
    last = NULL;
    count = 0;
}
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
// LinkListIterator.h

#ifndef H_LinkListIterator
#define H_LinkListIterator

# include "UnorderedLinkList.h"

# include <iostream>
using namespace std;

class LinkListIterator
{
    public:
        LinkListIterator();
        LinkListIterator(NodeType *ptr);
        int operator*(); // function to overload the dereferencing operator
        LinkListIterator operator++();// overloads the preincrement operator
        bool operator==(const LinkListIterator& right)const; // overloads the equal to operator
        bool operator!=(const LinkListIterator& right)const; // overloads the not equal to operator

    private:
        NodeType *current; // pointer to point to the current node in the ll

};
#endif 
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
// LinkListIterator.cpp

# include "LinkListIterator.h"

LinkListIterator::LinkListIterator()
{
    current = NULL;
}

LinkListIterator::LinkListIterator(NodeType *ptr)
{
    current = ptr;
}

int LinkListIterator::operator*()
{
    return current->info;
}

LinkListIterator LinkListIterator::operator++()
{
    current = current->link;
    return *this;
}

bool LinkListIterator::operator==(const LinkListIterator& right)const
{
    return(current == right.current);
}

bool LinkListIterator::operator!=(const LinkListIterator& right)const
{
    return (current != right.current);
}

Your headers are mutually inclusive. Only one of them can point to the other. To fix the inevitable compiler error: http://www.google.com/search?q=forward+declaration

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
//a.h
#include "b.h"

struct A{
    B *a;
};

//b.h
struct A;

struct B{
    A* a;
};

Last edited on

Thank you helios and Alvaro (cpp-home.com). Forward declaration solved the problem. I was trying to use NodeType and LinkListIterator before providing their definitions.

1
2
3
4
5
6
7
8
// LinkListIterator.h

class NodeType;

class LinkListIterator
{
    public:
...

1
2
3
4
5
6
7
8
// UnorderedLinkList.h

class LinkListIterator;

struct NodeType
{
    int info;
...

Last edited on

Topic archived. No new replies allowed.

The Arduino software is an open-source and easy to use platform which configures the Arduino board into functioning in a certain way. An Arduino code is written in C++ but with additional functions and methods. An Arduino is a hardware and software platform widely used in electronics.

In this article, we will see a few quick fixes for the error ‘does not name a type‘ or the ‘no such file or directory‘ error.

Also read: How to stop an Arduino program?


What does the error mean?

In almost every coding language known to man, every variable has a specific data type. In general, there are multiple data types like int indicating integer, float for decimal values, char and String for alphabets and sentences, boolean for true or false and many more. In Arduino, there are 16 data types commonly used.

  • void: Used in function declarations, and indicates that the function will not return anything.
  • boolean: It is a true or false value.
  • char: Stores a character value in one byte of the memory.
  • Unsigned char: Unsigned data type which encodes numbers between 0 and 255 and occupies one byte of the memory.
  • byte: It is an 8-bit unsigned number holding a value between 0 and 255.
  • int: It is a primary data type which stores a 16-bit integer value. It can store negative values.
  • Unsigned int: Unsigned integer that stores only positive integer values in the 2 byte memory.
  • long: It is a 32-bit memory for storing numbers, both positive and negative.
  • Unsigned long: Unsigned long variables store only positive numbers in the 32-bit memory storage.
  • short: It is a 16-bit data type storing positive and negative numbers.
  • float: It is a decimal value having a 32-bit memory.
  • double: It is a double floating number having either 32 or 64 bit memory depending on the board.
  • word: Based on the type of board, it stores either 16-bit or 32-bit unsigned number.
  • array: It is a collection of variables which is accessible using index numbers.
  • String-char array: Converts the string into an array of characters.
  • String-object: Class which can be used to manipulate, concatenate and perform other operations on strings and arrays.

The error ‘does not name a type‘ or the ‘no such file or directory‘ are errors that occur during the compilation process. They generally indicate missing data types or wrongly used data types. It may also indicate missing directories or libraries.

Also read: Arduino UNO vs Arduino Mega.


Here are two ways to fix the error.

Check data type

Every user-defined function and variable initialised or declared in the code should have a corresponding data type. The data type of the variable or function should also coincide with the value being stored or returned.

Consider a small example sample code below.

What is 'does not name a type' in Arduino: 2 Fixes

Here the function MQRead is of the type float. The variables i and mq_pin are integer type, while rs is float type. In the for loop, i is given the value 0, an integer value. The analogRead function always reads an integer value, which is being assigned to the mq_pin variable. Since the value or type for rs, the float type suffices for any value assigned to it as a result of the calculation. The user-defined function MQRead is of type float, which means that the return type for it is float, which is achieved by returning the value of rs for the function.

The error occurs if any of these data types don’t stand to the data being stored in the variables. Always check and recheck the data type for every variable, function and return type.


Library folder

In many cases, you may use libraries that are not standard or included in Arduino. But Arduino is flexible with the import of new libraries, making it easy to use all functions from any library. Follow the path below to check the currently available libraries in your Arduino software.

My Documents -> Arduino -> Libraries

Consider the snippet of code below. There are four library folders that are included for the code to work. But these aren’t a part of the standard library of Arduino.

What is 'does not name a type' in Arduino: 2 Fixes

There are two ways to import a library to the Arduino.


Method 1

Step 1: Click on Sketch on the top left panel of the window. Go to the include Library option and select Manage Libraries.

Keyboard Shortcut: Ctrl+Shift+I.

What is 'does not name a type' in Arduino: 2 Fixes

Step 2: Search or select from the options available and click on Install.

Note that a few Libraries may not be available if your software isn’t updated with the latest version.

What is 'does not name a type' in Arduino: 2 Fixes

All the libraries you are planning to use may not be easily found under the Manage Libraries section. In such cases, we use Method 2 for importing the libraries.


Method 2

Step 1: Download a zip file for the library from GitHub or any other reliable source present online.

Step 2: Click on Sketch on the top left panel of the window. Go to the include Library option and select Add ZIP Library.

What is 'does not name a type' in Arduino: 2 Fixes

Step 3: Set the file type to be ZIP files and folders.

Step 4: Go to the download location of the zip file and select it. Click on Open.

What is 'does not name a type' in Arduino: 2 Fixes

The library is successfully added to the Arduino software now.

Also read: NodeMCU vs Arduino vs Raspberry Pi.

При попытке написать этот код я получаю сообщение об ошибке "cin doesnt name a type",
Я не знаю, в чем конкретно проблема, и я попытался написать «используя пространство имен std;», но он выдал ту же ошибку.

Вот код

#include<iostream>

namespace myStuff {

int value = 0;

}

using namespace myStuff;

int main {

std::cout << "enter integer " << ;
std::cin >> value;
std::cout << "nyouhaveenterd a value" << value ;

return 0;

}

Вот ошибка компиляции:

: extended initializer lists only available with `-std=c++0x` or `-std=gnu++0x` [enabled by default]|
: expected primary-expression before ‘;’ token|
expected `}` before `;` token|
`cin` does not name a type|
: `cout` does not name a type|
: expected unqualified-id before `return`|
: expected declaration before `}` token|
||=== Build finished: 6 errors, 1 warnings ===|

1

Решение

int main{

должно быть

int main(){

а также

std::cout << "enter integer " << ;

должно быть

std::cout << "enter integer ";

7

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

На этой линии:

std::cout << "enter integer " << ;

Там нет соответствующего операнда, чтобы сделать утверждение синтаксически допустимым. Это, вероятно, источник ваших ошибок.

1

Это предыдущая строка.

 cout<<"enter integer" **<<** ;

что в прошлом << ожидает аргумент, который никогда не приводится

0

Contents

test local function definitions are illegal C++

Error C2660 : function does not take 3 arguments

Error LNK2019 unresolved external symbol

E0042 operand types are incompatible ( char and const char * )

E0025 quoted string should contain at least one character

error: ‘cout’ in namespace ‘std’ does not name a type

undefined reference to `std::cout’

Если начинается на C, то это ошибка компиллятора.

Если на L, то линкера.

test local function definitions are illegal C++

Появляется если Вы случайно определили функцию не перед main а внутри main.

Error C2660 : function does not take 3 arguments

Компилятор ждёт, что у функции будет другое количество аргументов.

Появляется, например, если Вы не подключили нужную функцию, но существует
функция перегрузка с другим количеством аргументов. Копилятор не находит
нужную функцию, находит ту у которой такое же название, пытается использовать,
но количество аргументов неправильно.

Error LNK2019 unresolved external symbol

Линкер видит, что вызывается функция, которая нигде не задана.

E0042 operand types are incompatible ( char and const char * )

Появляется обычно при сравнении char с символом в двойных кавычках.

Нужно заменить двойные кавычки одинарными

char s = line[0];

if (s == 'T') {
std::cout << "TopBicycle.ru" << std::endl;
}

E0025 quoted string should contain at least one character

Обычно появляется когда вы пытаетесь создать пустую строку но делаете это с одинарными кавычками.

Нужно заменить одинарные кавычки двойными.

empty_line = "";

‘cout’ in namespace ‘std’ does not name a type

error: ‘cout’ in namespace ‘std’ does not name a type

Скорее всего вы пытаетесь сделать вывод без функции

std::cout << «Hello»;

С++ на это ругается, поэтому нужно завернуть вывод в функцию

void log() {
std::cout << «Hello»;
}

undefined reference to `std::cout’

undefined reference to `std::cout’

Означает, что скорее всего вам нужен g++ а не gcc

Понравилась статья? Поделить с друзьями:
  • Error count canon
  • Error couldn t resolve host name
  • Error couldn t open file
  • Error couldn t open display null glxgears
  • Error couldn t open custom hpk