Error new types may not be defined in a return type

The above error is occurring on the line where I implement my constructor. I made a comment that points to that line. Any help greatly appreciated. #include #include <time.h&...

The above error is occurring on the line where I implement my constructor. I made a comment that points to that line. Any help greatly appreciated.

#include <vector>   
#include <time.h>      

class Stopwatch
{
    enum state {UNSTARTED, RUNNING, PAUSED, FINISHED};
    struct time
    {
        unsigned hours;
        unsigned minutes;
        unsigned seconds;
    };
    struct lap
    {
       unsigned n; // lap number
       time t; // lap time
       lap* next_ptr;
    };

    public: 
    Stopwatch();
    ~Stopwatch();
    void right_button(); // corresponds to start/stop/pause
    void left_button();  // corresponds to lap/reset

    private: 
    state cur_state;
    std::vector<lap> lapsvec;

}

Stopwatch::Stopwatch() // <--------- Here's where the compiler error is
{
    cur_state = UNSTARTED;
}

/* trivial destructor */
Stopwatch::~Stopwatch() 
{
}

int main()
{
    return 0;
}

I reviewed C++ constructors to see if I could figure out the problem. No luck.

asked Apr 24, 2014 at 23:24

user3566398's user avatar

1

You need a ; after the class declaration. Since you don’t have it, the class is not yet declared when the compiler reaches Stopwatch::Stopwatch(), thus complaining it’s a new type.

answered Apr 24, 2014 at 23:25

Paweł Stawarz's user avatar

Paweł StawarzPaweł Stawarz

3,8522 gold badges16 silver badges26 bronze badges

You are declaring a class, which doesn’t have a ; on the end:

 ...
    std::vector<lap> lapsvec;

};

That should fix it:

answered Apr 24, 2014 at 23:28

Mats Petersson's user avatar

Mats PeterssonMats Petersson

126k14 gold badges132 silver badges221 bronze badges

I keep getting the error in the title on this code and i can’t seem to figure out why. (The SDLGraphics class works ok because i have tested it separately.)


SDLCharacter::SDLCharacter(SDLGraphics* graphics, int imgX, int imgY, int imgW, int imgH,
				 int TransparentRed, int TransparentBlue, int TransparentGreen, 
				 string filename, float maxspeed, int posX, int posY, float angle)
{
	m_graphics=graphics;
	m_imgX=imgX;
	m_imgY=imgY;
	m_height=imgH;
	m_width=imgW;
	m_posX=posX;
	m_posY=posY;
	m_maxspd=maxspeed;
	m_currentspdX=0;
	m_currentspdY=0;
	m_currentAngle=angle;
	m_graphics->imageLoad(filename, TransparentRed, TransparentBlue, TransparentGreen);
	m_image=m_graphics->screenReturn();
	
}

any ideas are apreciated :)

«Try not to become a man of success but rather to become a man of value.» — Albert Einstein

What error do you get, and on which line? Is it a runtime or compilation error?

That error is typically caused by forgetting a semicolon at the end of a class / struct / union…

In Compile time (somewhat a stupid question)? What line does the error point to?

EDIT: Ow. Beat by two people in under a minute.

Projects:> Thacmus — CMS (PHP 5, MySQL)Paused:> dgi> MegaMan X Crossfire

the error is in the title of the topic… and it’s a compilation one.

it’s weird because the ide (eclipse) shows me the error on the line where the paranthesis
( «{» ) starts, right after declaring the parameters.

«Try not to become a man of success but rather to become a man of value.» — Albert Einstein

Quote:Original post by Hypherion
the error is in the title of the topic… and it’s a compilation one.

it’s weird because the ide (eclipse) shows me the error on the line where the paranthesis
( «{» ) starts, right after declaring the parameters.

But what does it actually say? Missing semicolon? Unknown type? Something else?

You haven’t specified a return type for your method in the implementation shown. What return type did you specify when declaring the method in the header?

EDIT: Nevermind, it’s the constructor I see know ^^

Best regards, Omid

«error: return type specification for constructor invalid» -> this is the other error i get and they both redirect me one to the other :| .

«Try not to become a man of success but rather to become a man of value.» — Albert Einstein

Quote:Original post by Hypherion
«error: return type specification for constructor invalid» -> this is the other error i get and they both redirect me one to the other :| .

Can you show us the code where you declare the constructor in the header?

Best regards, Omid

Quote:Original post by rip-off
That error is typically caused by forgetting a semicolon at the end of a class / struct / union…

I think you’ll find this is the answer. Try adding a semicolon to the end of your SDLCharacter class:

class SDLCharacter{public:    SDLCharacter(...);    void foo();    void bar();}; //  <--- HERE 

polimorf96

9 / 9 / 1

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

Сообщений: 270

1

где ошибка?

14.11.2010, 00:58. Показов 4169. Ответов 9

Метки нет (Все метки)


Компилятор ругается :
D:c++test2main.cpp||In constructor ‘String::String(char*, int)’:|
D:c++test2main.cpp|20|warning: comparison between signed and unsigned integer expressions|
D:c++test2main.cpp|5|error: new types may not be defined in a return type|
D:c++test2main.cpp|5|note: (perhaps a semicolon is missing after the definition of ‘String’)|
D:c++test2main.cpp|74|error: two or more data types in declaration of ‘main’|
||=== Build finished: 2 errors, 1 warnings ===|

хотел создать «породие» на класс string чисто в целях обучения но не могу понять почему ошибка то?

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

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
#include <iostream>
#include <cstring>
using namespace std;
 
class String
{
    private:
    char * arr;
    int nof;
    public:
    String(char s[])
    {
 
        nof = strlen(s);
        arr = new char [nof+1];
        strcpy(arr,s);
    }
    String (char s[],int numberof)
    {
        nof = (strlen(s) < numberof) ? strlen(s) : numberof;
        arr = new char [nof+1];
    }
 
    String ()
    {
        nof = 255;
        arr = new char [nof];
    }
    ~String()
    {
        delete [] arr;
    }
    int length()
    {
        return nof;
    }
    void operator = (String s1)
    {
        if (nof  >= s1.nof)
        strcpy(arr,s1.arr);
    }
    bool operator == (String s1)
    {
        if (nof != s1.nof) return 0;
        for (int j;j<nof;j++)
        {
            if (arr[j] != s1[j]) return 0;
        }
        return 1;
    }
    char& operator [] (int j)
    {
        if ((j>nof+1) or (j<0))
        {
            cout << "Error!" << endl;
        }
        else
        {
            return *(arr+j);
        }
    }
    String operator + (String s1)
    {
        String s2 = s1;
        strcat(s2.arr,arr);
        return s2;
    }
 
 
 
    }
 
 
int main()
{
 
    return 0;
}

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



0



alex_x_x

бжни

2473 / 1684 / 135

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

Сообщений: 7,162

14.11.2010, 01:03

2

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
 
#include <iostream>
#include <cstring>
using namespace std;
 
class String
{
    private:
    char * arr;
    int nof;
    public:
    String(char s[])
    {
 
        nof = strlen(s);
        arr = new char [nof+1];
        strcpy(arr,s);
    }
    String (char s[],size_t numberof)
    {
        nof = (strlen(s) < numberof) ? strlen(s) : numberof;
        arr = new char [nof+1];
    }
 
    String ()
    {
        nof = 255;
        arr = new char [nof];
    }
    ~String()
    {
        delete [] arr;
    }
    int length()
    {
        return nof;
    }
    void operator = (String s1)
    {
        if (nof  >= s1.nof)
        strcpy(arr,s1.arr);
    }
    bool operator == (String s1)
    {
        if (nof != s1.nof) return 0;
        for (int j;j<nof;j++)
        {
            if (arr[j] != s1[j]) return 0;
        }
        return 1;
    }
    char& operator [] (int j)
    {
        if ((j>nof+1) or (j<0))
        {
            cout << "Error!" << endl;
        }
        else
        {
            return *(arr+j);
        }
    }
    String operator + (String s1)
    {
        String s2 = s1;
        strcat(s2.arr,arr);
        return s2;
    }
 
 
 
};
 
 
int main()
{
 
    return 0;
}



0



ForEveR

В астрале

Эксперт С++

8048 / 4805 / 655

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

Сообщений: 10,562

14.11.2010, 01:05

3

; после определения класса забыли.
+ вместо or лучше юзать ||

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
#include <iostream>
#include <cstring>
using namespace std;
 
class String
{
    private:
    char * arr;
    int nof;
    public:
    String(char s[])
    {
 
        nof = strlen(s);
        arr = new char [nof+1];
        strcpy(arr,s);
    }
    String (char s[],int numberof)
    {
        nof = (strlen(s) < numberof) ? strlen(s) : numberof;
        arr = new char [nof+1];
    }
 
    String ()
    {
        nof = 255;
        arr = new char [nof];
    }
    ~String()
    {
        delete [] arr;
    }
    int length()
    {
        return nof;
    }
    void operator = (String s1)
    {
        if (nof  >= s1.nof)
        strcpy(arr,s1.arr);
    }
    bool operator == (String s1)
    {
        if (nof != s1.nof) return 0;
        for (int j;j<nof;j++)
        {
            if (arr[j] != s1[j]) return 0;
        }
        return 1;
    }
    char& operator [] (int j)
    {
        if ((j>nof+1) || (j<0))
        {
            cout << "Error!" << endl;
        }
        else
        {
            return *(arr+j);
        }
    }
    String operator + (String s1)
    {
        String s2 = s1;
        strcat(s2.arr,arr);
        return s2;
    }
 
 
 
    };
 
int main()
{
 
    return 0;
}



0



5 / 5 / 4

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

Сообщений: 24

14.11.2010, 01:06

4

И еще в С++ нет оператора or так что замените его на ||



0



бжни

2473 / 1684 / 135

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

Сообщений: 7,162

14.11.2010, 01:08

5

кстати интересно что компилятор на [] не выдает, что не все пути возвращают значения

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

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

И еще в С++ нет оператора or так что замените его на ||

есть)) xor, and, not есть
синонимы, а по факту дефайны обычно



0



В астрале

Эксперт С++

8048 / 4805 / 655

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

Сообщений: 10,562

14.11.2010, 01:08

6

Но не везде. В студии нету к примеру)



0



бжни

2473 / 1684 / 135

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

Сообщений: 7,162

14.11.2010, 01:13

7

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

Но не везде. В студии нету к примеру)

_______________

The <iso646.h> header shall define the following eleven macros (on the left) that expand to the corresponding tokens (on the right):
and
&&
and_eq
&=
bitand
&
bitor
|
compl
˜
not
!
not_eq
!=
or
||
or_eq
|=
xor
^
xor_eq
^=

Добавлено через 2 минуты
поэтому gcc у меня и скушал код



2



В астрале

Эксперт С++

8048 / 4805 / 655

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

Сообщений: 10,562

14.11.2010, 01:18

8

alex_x_x, Снимаю шляпу. Не подозревал о таком хедере. Спасибо за информацию!



0



polimorf96

9 / 9 / 1

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

Сообщений: 270

14.11.2010, 17:03

 [ТС]

9

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

; после определения класса забыли.
+ вместо or лучше юзать ||

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
#include <iostream>
#include <cstring>
using namespace std;
 
class String
{
    private:
    char * arr;
    int nof;
    public:
    String(char s[])
    {
 
        nof = strlen(s);
        arr = new char [nof+1];
        strcpy(arr,s);
    }
    String (char s[],int numberof)
    {
        nof = (strlen(s) < numberof) ? strlen(s) : numberof;
        arr = new char [nof+1];
    }
 
    String ()
    {
        nof = 255;
        arr = new char [nof];
    }
    ~String()
    {
        delete [] arr;
    }
    int length()
    {
        return nof;
    }
    void operator = (String s1)
    {
        if (nof  >= s1.nof)
        strcpy(arr,s1.arr);
    }
    bool operator == (String s1)
    {
        if (nof != s1.nof) return 0;
        for (int j;j<nof;j++)
        {
            if (arr[j] != s1[j]) return 0;
        }
        return 1;
    }
    char& operator [] (int j)
    {
        if ((j>nof+1) || (j<0))
        {
            cout << "Error!" << endl;
        }
        else
        {
            return *(arr+j);
        }
    }
    String operator + (String s1)
    {
        String s2 = s1;
        strcat(s2.arr,arr);
        return s2;
    }
 
 
 
    };
 
int main()
{
 
    return 0;
}

точно блин такая ошибка дурацка! СПАСИБО!

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

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

кстати интересно что компилятор на [] не выдает, что не все пути возвращают значения

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

есть)) xor, and, not есть
синонимы, а по факту дефайны обычно

кстати интересно что компилятор на [] не выдает, что не все пути возвращают значения
-немного не понял тебя…
а вроде того что функция с возвращаемым значением обязана что-то вренуть в любом случае -так чтоли?



0



бжни

2473 / 1684 / 135

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

Сообщений: 7,162

15.11.2010, 00:02

10

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

обязана что-то вренуть в любом случае -так чтоли?

как-то так



0



IT_Exp

Эксперт

87844 / 49110 / 22898

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

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

15.11.2010, 00:02

10

    msm.ru

    Нравится ресурс?

    Помоги проекту!

    >
    Ошибка при определении конструктора
    , Не могу понять, в чем дело

    • Подписаться на тему
    • Сообщить другу
    • Скачать/распечатать тему



    Сообщ.
    #1

    ,
    13.12.09, 11:31

      Добрый день. Проблема в следующем: есть класс fclass, который содержит в себе файловый поток для ввода file_stor, переменные s_byte, s_kbyte, s_mbyte, хранящие в себе размер этого самого файла соответсвенно в байтах, килобайтах и мегабайтах, и функции получения этих размеров. При определении конструктора, который передает значения в конструктор для file_stor, компилятор пишет ошибки «New types may not be defined in a return type» и «Return type specification for constructor invalid». Не понимаю, откуда там могут взяться эти ошибки? Помогите разобраться.

      ExpandedWrap disabled

        #include <iostream.h>

        #include <fstream.h>

        using namespace std;

        class fclass

        {

         protected:

            ifstream file_stor;

           int   s_byte;

           double s_kbyte;

           double s_mbyte;

         public:

            fclass(char *);

           int   state;

           int   get_b();

           double get_kb();

           double get_mb();

        }

        fclass::fclass(char *str): file_stor(str) //Здесь ошибка

        {

         char c;

         if(!file_stor)

         {

           state=0;

           s_byte=0;

           s_kbyte=s_mbyte=0;

         }

         else

         {

           state=1;

           //Подсчет длины файла в байтах

           s_byte=0;

           while(!file_stor.eof())

           {

            file_stor.get(c);

                s_byte++;

           }

           //В килобайтах

           s_kbyte=(double)s_byte / 1024.0;

           //В мегабайтах

           s_mbyte=s_kbyte / 1024.0;

         }

        }

      Вот сейчас подумал, а может сделать класс fclass производным от класса ifstream, добавив в него поля с размерами файла?

      Пишу в Dev-C++ под XP

      Сообщение отредактировано: 001 — 13.12.09, 11:34


      bobjones



      Сообщ.
      #2

      ,
      13.12.09, 12:00

        точку с запятой после определения класса


        001



        Сообщ.
        #3

        ,
        13.12.09, 13:44

          Ч0рт, точно, спасибо :)

          0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

          0 пользователей:

          • Предыдущая тема
          • C/C++: Общие вопросы
          • Следующая тема

          Рейтинг@Mail.ru

          [ Script execution time: 0,0457 ]   [ 16 queries used ]   [ Generated: 12.02.23, 18:16 GMT ]  

          Понравилась статья? Поделить с друзьями:

          Читайте также:

        • Error networkmanager is not running
        • Error forming pointer to reference type
        • Error networkerror when attempting to fetch resource перевод
        • Error formerr resolving
        • Error network request failed перевод

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

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