Ошибка definition of implicitly declared

I’m writing this linked list program with C++

When I test the program, I got the error

linkedlist.cpp:5:24: error: definition of implicitly-declared ‘constexpr LinkedList::LinkedList()’
LinkedList::LinkedList(){

Here’s the code

linkedlist.h file:

#include "node.h"
using namespace std;

class LinkedList {
  Node * head = nullptr;
  int length = 0;
public:
  void add( int );
  bool remove( int );
  int find( int );
  int count( int );
  int at( int );
  int len();
};

linkedlist.cpp file:

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

LinkedList::LinkedList(){
  length = 0;
  head = NULL;
}
/*and all the methods below*/

please help.

CinCout's user avatar

CinCout

9,48511 gold badges49 silver badges67 bronze badges

asked Nov 3, 2017 at 9:40

Leslie Zhou's user avatar

1

Declare the parameterless constructor in the header file:

class LinkedList {
{
....
public:
    LinkedList();
    ....
}

You are defining it in the .cpp file without actually declaring it. But since the compiler provides such a constructor by default (if no other constructor is declared), the error clearly states that you are trying to define an implicitly-declared constructor.

answered Nov 3, 2017 at 9:41

CinCout's user avatar

CinCoutCinCout

9,48511 gold badges49 silver badges67 bronze badges

2

You should declare the constructor inside the class inorder to define the cunstructor outside the class. Otherwise you should define it inside the class itself.Your class should look like this.

            #include "node.h"
            using namespace std;
            class LinkedList {
              Node * head = nullptr;
              int length = 0;
            public:
              LinkedList();
              void add( int );
              bool remove( int );
              int find( int );
              int count( int );
              int at( int );
              int len();
            };

answered Aug 19, 2020 at 5:40

JOSEPH BENOY's user avatar

To define constructor outside the class you need to declare it first in public specifier then define it outside the class.

#include "node.h"
using namespace std;

class LinkedList {
  Node * head = nullptr;
  int length = 0;
public:
  LinkedList();
  void add( int );
  bool remove( int );
  int find( int );
  int count( int );
  int at( int );
  int len();
};


LinkedList::LinkedList(){
  length = 0;
  head = NULL;
}

answered Aug 19, 2020 at 5:30

Divya Barvekar's user avatar

definition of implicitly-declared `ElArea::ElArea()

Я подозреваю, что в объявлении класса не объявлен конструктор.  об этом говорит implicitly-declared

Я попробовал скомпилировать такой пример:

class ElArea {
public:
    int x;
};

ElArea::ElArea() {
    x = 1;
}

Получил аналогичную ошибку

try.cpp:8: error: definition of implicitly-declared `ElArea::ElArea()’
try.cpp:8: error: declaration of `ElArea::ElArea()’ throws different exceptions
try.cpp:2: error: than previous declaration `ElArea::ElArea() throw ()’

Если в объявление класса добавить конструктор, то всё компилируется

class ElArea {
public:
    int x;
    ElArea();
};

/*********************************************************************** CSCI 240 Program 10 Fall 2016

Programmer: Billythong Trinh

Section:

Date Due:12/2/2016

Purpose: ***********************************************************************/

include <iostream>

include <iomanip>

include <cstdlib>

include <fstream>

using namespace std;

//Place the class definition after this line

class LoShuMagicSquare { public: void fillSquare (const char[]); void printSquare(); bool isMagic();

const static int maxRows = 3;
const static int maxColumns = 3;
int  board[3][3];
int magic;
int row1 = board[0][0] + board[0][1] + board[0][2];
int row2 = board[1][0]+ board[1][1] + board[1][2];
int row3 = board[2][0]+ board[2][1] + board[2][2];
int column1 = board[0][0] + board[1][0] + board[2][0];
int column2 = board[0][1] + board[1][1] + board[2][1];
int column3 = board[0][2] + board[1][2] + board[2][2];
int downDiagonal = board[0][0] + board[1][1] + board[2][2];
int updiagonal = board[2][0] + board[1][1] + board[0][2];

};

int main() { //Create a LoShuMagicSquare object that will be used to test the 4 puzzles LoShuMagicSquare puzzle;

//Puzzle 1 using loshu_puzzle1.txt. The object will be filled, displayed,
//and then tested to see if it is a valid solution

cout << "Puzzle 1:" << endl << endl;
puzzle.fillSquare( "loshu_puzzle1.txt");

puzzle.printSquare();

cout << endl << "Is it magic? " << ( puzzle.isMagic() ? "Yes": "No" ) << endl << endl << endl;


//Puzzle 2 using loshu_puzzle2.txt. The object will be filled, displayed,
//and then tested to see if it is a valid solution
cout << "Puzzle 2:" << endl << endl;

puzzle.fillSquare( "loshu_puzzle2.txt");

puzzle.printSquare();

cout << endl << "Is it magic? " << ( puzzle.isMagic() ? "Yes": "No" ) << endl << endl << endl;


//Puzzle 3 using loshu_puzzle3.txt. The object will be filled, displayed,
//and then tested to see if it is a valid solution
cout << "Puzzle 3:" << endl << endl;

puzzle.fillSquare( "loshu_puzzle3.txt");

puzzle.printSquare();

cout << endl << "Is it magic? " << ( puzzle.isMagic() ? "Yes": "No" ) << endl << endl << endl;


//Puzzle 4 using loshu_puzzle4.txt. The object will be filled, displayed,
//and then tested to see if it is a valid solution
cout << "Puzzle 4:" << endl << endl;

puzzle.fillSquare( "loshu_puzzle4.txt");

puzzle.printSquare();

cout << endl << "Is it magic? " << ( puzzle.isMagic() ? "Yes": "No" ) << endl << endl << endl;


return 0;

}

//Code the methods below this line

LoShuMagicSquare::LoShuMagicSquare() { char board [3][3] = { { ‘0’, ‘0’, ‘0’,}, { ‘0’, ‘0’, ‘0’ }, { ‘0’, ‘0’, ‘0’ } }; }

void LoShuMagicSquare:: fillSquare(const char[]) {

}

void LoShuMagicSquare:: printSquare() {

    string Line = "";
    
    cout << endl;
    
    for (int k = 0; k < 3; k++)
    {
        Line = "";
        
        for (int l = 0; l < 3; l++)
        {
          cout << board[k][l] << " ";
        }
        
        cout << endl;
        if (k < 2) cout << "-----" << endl;
    }
    
    cout << endl;

}

bool LoShuMagicSquare:: isMagic() { magic = false;

//Check vertical and horizontal to see if there is a winner
for (int k = 0; k < 3; k++)
{
    if (row1 == row2 && row1 == row3 && row2 == row3)
        magic = true;
    if (column1 == column2 && column1 == column3 && column2 == column3)
        magic = true;
}

//Check diagonal to see if there is a winner
if (downDiagonal == updiagonal)
    magic = true;

return true;

}

В объявлении класса (возможно, в заголовочном файле) вам нужно что-то похожее на:

class StackInt {
public:
    StackInt();
    ~StackInt();  
}

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

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

Вы можете увидеть это, используя очень простое:

class X {
        public: X();   // <- remove this.
};
X::X() {};
int main (void) { X x ; return 0; }

Скомпилируйте это, и это работает. Затем удалите строку с маркером комментария и скомпилируйте снова. Вы увидите, что ваши проблемы появятся тогда:

class X {};
X::X() {};
int main (void) { X x ; return 0; }
qq.cpp:2: error: definition of implicitly-declared `X::X()'

ответ дан paxdiablo 1 March 2013 в 15:48

поделиться

Я пишу код для своих классов и у меня есть ошибка, с которой я не могу справиться. Ошибки заключаются в следующем. Также я не могу ничего менять в основном файле:

In file included from lab13.cpp:15:0:
lab13.h: In member function ‘TSeries& TSeries::operator()(int, int)’:
lab13.h:10:39: warning: no return statement in function returning non-void [-Wreturn-type]
TSeries &operator()(int, int){}
^
g++ -c -Wall lab13f.cpp
In file included from lab13f.cpp:1:0:
lab13.h:15:10: error: ‘ostream’ in namespace ‘std’ does not name a type
friend std::ostream &operator<<(std::ostream &o,const TSeries &ts);
^
lab13.h: In member function ‘TSeries& TSeries::operator()(int, int)’:
lab13.h:10:39: warning: no return statement in function returning non-void [-Wreturn-type]
TSeries &operator()(int, int){}
^
lab13f.cpp: At global scope:
lab13f.cpp:13:9: error: prototype for ‘TSeries TSeries::operator()(int, int)’ does not match any in class ‘TSeries’
TSeries TSeries::operator()(int, int){}
^
In file included from lab13f.cpp:1:0:
lab13.h:10:18: error: candidate is: TSeries& TSeries::operator()(int, int)
TSeries &operator()(int, int){}
^
lab13f.cpp:16:9: error: prototype for ‘TSeries TSeries::operator+(TSeries&)’ does not match any in class ‘TSeries’
TSeries TSeries::operator+(TSeries &ts){
^
In file included from lab13f.cpp:1:0:
lab13.h:9:17: error: candidate is: const TSeries TSeries::operator+(const TSeries&) const
const TSeries operator+(const TSeries &ts)const;
^
lab13f.cpp:45:19: error: definition of implicitly-declared ‘TSeries::~TSeries()’
TSeries::~TSeries(){}
^
lab13f.cpp: In member function ‘TSeries& TSeries::operator=(TSeries (*)(int, int))’:
lab13f.cpp:47:52: warning: no return statement in function returning non-void [-Wreturn-type]
TSeries &TSeries::operator=(TSeries(int a, int b)){}
^
lab13f.cpp: In function ‘std::ostream& operator<<(std::ostream&, const TSeries&)’:

lab13f.cpp:51:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
make: *** [lab13f.o] Błąd 1

Я потратил пару дней, пытаясь решить проблему, и наконец сдался. Надеюсь, кто-нибудь поможет мне в моей борьбе 🙂 Я был бы очень благодарен.


Я забыл добавить, что основной файл был написан преподавателем, и ни при каких обстоятельствах мне не разрешено изменять НИЧЕГО в нем.

0

Решение

Линия

    TSeries &operator=(TSeries(int a, int b));

объявляет функцию, аргумент которой является функцией с двумя входами типа int и тип возвращаемого значения TSeries,

Я не думаю, что ты хотел это сделать.

Оператор присваивания копии будет объявлен с синтаксисом:

    TSeries &operator=(TSeries const& rhs);

Также не понятно, что вы имели в виду в строке:

     TSeries series4=series1(2,4);

Возможно, вы хотели использовать:

     // Will use the compiler generated copy constructor
// since you haven't declared one.
TSeries series4=series1;

или же

     // Will use the constructor that takes two ints
TSeries series4(2,4);

1

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

Может быть, это опечатка. Это:

TSeries series4=series1(2,4);

не создает series4 с аргументами конструктора 2 а также 4, но вместо этого он пытается позвонить series1‘s (ПРИМЕЧАНИЕ: это переменная) operator()(int, int), И такого оператора не определено.

Я думаю тебе нужно

TSeries series4=TSeries(2,4);

Или даже лучше:

TSeries series4(2,4);

Кроме того, конструкции, как это:

series1+=1.,0.,3.;

на самом деле позвонит operator += только однажды. Просто чтобы быть ясно, так как я не уверен, ожидаете ли вы этого. Вы можете прочитать о operator, в C ++.
Итак, если вы хотите 3 дополнения, вам нужно:

series1+=1.;
series1+=0.;
series1+=3.;

Также обратите внимание на ответ @ RSahu о operator=, за что я проголосовал (хороший улов, я этого не заметил).

1

Компилятор жалуется, потому что series1 (2,4) вызывает TSeries :: operator () (int, int), который отсутствует, а не конструктор TSeries (int, int)

0

  1. D:Qt4.4.0examplesdialogssipdialog>nmake

  2. Microsoft (R) Program Maintenance Utility Version 9.00.21022.08

  3. Copyright (C) Microsoft Corporation. All rights reserved.

  4. "C:ProgrammiMicrosoft Visual Studio 9.0VCBINnmake.exe" -f Makefile.

  5. Debug all

  6. Microsoft (R) Program Maintenance Utility Version 9.00.21022.08

  7. Copyright (C) Microsoft Corporation. All rights reserved.

  8. g++ -c -g -frtti -fexceptions -mthreads -Wall -DUNICODE -DQT_LARGEFILE_S

  9. UPPORT -DQT_DLL -DQT_GUI_LIB -DQT_CORE_LIB -DQT_THREAD_SUPPORT -DQT_NEEDS_QMAIN

  10. -I'../../../include/QtCore' -I'../../../include/QtCore' -I'../../../include/QtGu

  11. i' -I'../../../include/QtGui' -I'../../../include' -I'.' -I'd:/Qt/4.4.0/include/

  12. ActiveQt' -I'tmp/moc/debug_shared' -I'.' -I'../../../mkspecs/win32-g++' -o tmp/o

  13. bj/debug_shared/dialog.o dialog.cpp

  14. dialog.cpp:44:17: QtGui: No such file or directory

  15. In file included from dialog.cpp:46:

  16. dialog.h:47:19: QDialog: No such file or directory

  17. In file included from dialog.cpp:46:

  18. dialog.h:51: error: expected class-name before '{' token

  19. dialog.h:54: error: ISO C++ forbids declaration of `Q_OBJECT' with no type

  20. dialog.h:54: error: expected `;' before "public"

  21. dialog.h:59: error: `QRect' does not name a type

  22. dialog.h:61: error: expected `:' before "slots"

  23. dialog.h:62: error: expected primary-expression before "void"

  24. dialog.h:62: error: ISO C++ forbids declaration of `slots' with no type

  25. dialog.h:62: error: expected `;' before "void"

  26. dialog.cpp:50: error: definition of implicitly-declared `Dialog::Dialog()'

  27. dialog.cpp:50: error: declaration of `Dialog::Dialog()' throws different excepti

  28. ons

  29. dialog.h:51: error: than previous declaration `Dialog::Dialog() throw ()'

  30. dialog.cpp: In constructor `Dialog::Dialog()':

  31. dialog.cpp:51: error: `desktopGeometry' was not declared in this scope

  32. dialog.cpp:51: error: `QApplication' has not been declared

  33. dialog.cpp:51: error: `desktop' was not declared in this scope

  34. dialog.cpp:53: error: `tr' was not declared in this scope

  35. dialog.cpp:53: error: `setWindowTitle' was not declared in this scope

  36. dialog.cpp:54: error: `QScrollArea' was not declared in this scope

  37. dialog.cpp:54: error: `scrollArea' was not declared in this scope

  38. dialog.cpp:54: error: `QScrollArea' is not a type

  39. dialog.cpp:55: error: `QGroupBox' was not declared in this scope

  40. dialog.cpp:55: error: `groupBox' was not declared in this scope

  41. dialog.cpp:55: error: `QGroupBox' is not a type

  42. dialog.cpp:57: error: `QGridLayout' was not declared in this scope

  43. dialog.cpp:57: error: `gridLayout' was not declared in this scope

  44. dialog.cpp:57: error: `QGridLayout' is not a type

  45. dialog.cpp:62: error: `QLineEdit' was not declared in this scope

  46. dialog.cpp:62: error: `lineEdit' was not declared in this scope

  47. dialog.cpp:62: error: `QLineEdit' is not a type

  48. dialog.cpp:66: error: `QLabel' was not declared in this scope

  49. dialog.cpp:66: error: `label' was not declared in this scope

  50. dialog.cpp:66: error: `QLabel' is not a type

  51. dialog.cpp:70: error: `QPushButton' was not declared in this scope

  52. dialog.cpp:70: error: `button' was not declared in this scope

  53. dialog.cpp:70: error: `QPushButton' is not a type

  54. dialog.cpp:88: error: `QHBoxLayout' was not declared in this scope

  55. dialog.cpp:88: error: `layout' was not declared in this scope

  56. dialog.cpp:88: error: `QHBoxLayout' is not a type

  57. dialog.cpp:90: error: `setLayout' was not declared in this scope

  58. dialog.cpp:91: error: `Qt' has not been declared

  59. dialog.cpp:91: error: `ScrollBarAlwaysOff' was not declared in this scope

  60. dialog.cpp:95: error: `pressed' was not declared in this scope

  61. dialog.cpp:95: error: `SIGNAL' was not declared in this scope

  62. dialog.cpp:96: error: `qApp' was not declared in this scope

  63. dialog.cpp:96: error: `closeAllWindows' was not declared in this scope

  64. dialog.cpp:96: error: `SLOT' was not declared in this scope

  65. dialog.cpp:96: error: `connect' was not declared in this scope

  66. dialog.cpp:97: error: `QApplication' has not been declared

  67. dialog.cpp:97: error: expected primary-expression before "int"

  68. dialog.cpp:97: error: `workAreaResized' was not declared in this scope

  69. dialog.cpp:98: error: expected primary-expression before "int"

  70. dialog.cpp:98: error: `desktopResized' was not declared in this scope

  71. dialog.cpp:53: warning: unused variable 'setWindowTitle'

  72. dialog.cpp:54: warning: unused variable 'QScrollArea'

  73. dialog.cpp:55: warning: unused variable 'QGroupBox'

  74. dialog.cpp:57: warning: unused variable 'QGridLayout'

  75. dialog.cpp:62: warning: unused variable 'QLineEdit'

  76. dialog.cpp:66: warning: unused variable 'QLabel'

  77. dialog.cpp:70: warning: unused variable 'QPushButton'

  78. dialog.cpp:88: warning: unused variable 'QHBoxLayout'

  79. dialog.cpp:90: warning: unused variable 'setLayout'

  80. dialog.cpp:91: warning: unused variable 'ScrollBarAlwaysOff'

  81. dialog.cpp:95: warning: unused variable 'pressed'

  82. dialog.cpp:96: warning: unused variable 'qApp'

  83. dialog.cpp:96: warning: unused variable 'closeAllWindows'

  84. dialog.cpp:97: warning: unused variable 'workAreaResized'

  85. dialog.cpp:98: warning: unused variable 'desktopResized'

  86. dialog.cpp: At global scope:

  87. dialog.cpp:104: error: no `void Dialog::desktopResized(int)' member function dec

  88. lared in class `Dialog'

  89. dialog.cpp: In member function `void Dialog::reactToSIP()':

  90. dialog.cpp:114: error: `QRect' was not declared in this scope

  91. dialog.cpp:114: error: expected `;' before "availableGeometry"

  92. dialog.cpp:116: error: `desktopGeometry' was not declared in this scope

  93. dialog.cpp:116: error: `availableGeometry' was not declared in this scope

  94. dialog.cpp:118: error: `windowState' was not declared in this scope

  95. dialog.cpp:118: error: `Qt' has not been declared

  96. dialog.cpp:118: error: `WindowMaximized' was not declared in this scope

  97. dialog.cpp:118: error: `setWindowState' was not declared in this scope

  98. dialog.cpp:119: error: `setGeometry' was not declared in this scope

  99. dialog.cpp:118: warning: unused variable 'windowState'

  100. dialog.cpp:118: warning: unused variable 'WindowMaximized'

  101. dialog.cpp:118: warning: unused variable 'setWindowState'

  102. dialog.cpp:119: warning: unused variable 'setGeometry'

  103. dialog.cpp:121: error: `windowState' was not declared in this scope

  104. dialog.cpp:121: error: `Qt' has not been declared

  105. dialog.cpp:121: error: `WindowMaximized' was not declared in this scope

  106. dialog.cpp:121: error: `setWindowState' was not declared in this scope

  107. dialog.cpp:121: warning: unused variable 'windowState'

  108. dialog.cpp:121: warning: unused variable 'WindowMaximized'

  109. dialog.cpp:121: warning: unused variable 'setWindowState'

  110. dialog.cpp:124: error: `desktopGeometry' was not declared in this scope

  111. dialog.cpp:124: error: `availableGeometry' was not declared in this scope

  112. dialog.cpp:114: warning: unused variable 'QRect'

  113. dialog.cpp:124: warning: unused variable 'desktopGeometry'

  114. dialog.cpp:124: warning: unused variable 'availableGeometry'

  115. NMAKE : fatal error U1077: 'C:MinGWbing++.EXE' : return code '0x1'

  116. Stop.

  117. NMAKE : fatal error U1077: '"C:ProgrammiMicrosoft Visual Studio 9.0VCBINnma

  118. ke.exe"' : return code '0x2'

  119. Stop.

Declare the parameterless constructor in the header file:

class LinkedList {
{
....
public:
    LinkedList();
    ....
}

You are defining it in the .cpp file without actually declaring it. But since the compiler provides such a constructor by default (if no other constructor is declared), the error clearly states that you are trying to define an implicitly-declared constructor.

You should declare the constructor inside the class inorder to define the cunstructor outside the class. Otherwise you should define it inside the class itself.Your class should look like this.

            #include node.h
            using namespace std;
            class LinkedList {
              Node * head = nullptr;
              int length = 0;
            public:
              LinkedList();
              void add( int );
              bool remove( int );
              int find( int );
              int count( int );
              int at( int );
              int len();
            };

C++ error: definition of implicitly-declared

To define constructor outside the class you need to declare it first in public specifier then define it outside the class.

#include node.h
using namespace std;

class LinkedList {
  Node * head = nullptr;
  int length = 0;
public:
  LinkedList();
  void add( int );
  bool remove( int );
  int find( int );
  int count( int );
  int at( int );
  int len();
};


LinkedList::LinkedList(){
  length = 0;
  head = NULL;
}

c++compiler-errorsqt

Hello everyone having anissue with my code today. I have created a program calculating area of square circle and rectangle. With a base class of shape. Where the UML has shape as the abstract class with public area():double, getName():string,and getDimensions:string, rectangle derived from shape with protected height, and width, and a public rectangle(h:double, w:double), followed by a derived square from rectangle with just a public square(h:double), and finally a circle derived from shape with a private radius, and a public circle(r:double).
So far have gotten far in my code yet in my shape.cpp file am getting an error on line 10 that says shape.cpp:10: error: definition of implicitly-declared ‘constexpr shape::shape()’
shape::shape()

here is a link to my complete code: https://gist.github.com/anonymous/0eedd7719a34655488fb

shape.cpp file:

#include "shape.h"
#include "circle.h"
#include "rectangle.h"
#include "square.h"
#include <QDebug>
#include <QString>
#include <iostream>
using namespace std;

shape::shape()
{

};

your help is appreciated

Возможно, вам также будет интересно:

  • Ошибка defaults loaded как исправить
  • Ошибка default radeon wattman settings have been restored due to an unexpected system failure
  • Ошибка default boot device missing or boot failed acer
  • Ошибка defaillant antivol на ситроен с4
  • Ошибка def на газовом котле

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

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