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
9,48511 gold badges49 silver badges67 bronze badges
asked Nov 3, 2017 at 9:40
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
![]()
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
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
![]()
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
D:Qt4.4.0examplesdialogssipdialog>nmake
Microsoft (R) Program Maintenance Utility Version 9.00.21022.08
Copyright (C) Microsoft Corporation. All rights reserved.
"C:ProgrammiMicrosoft Visual Studio 9.0VCBINnmake.exe" -f Makefile.
Debug all
Microsoft (R) Program Maintenance Utility Version 9.00.21022.08
Copyright (C) Microsoft Corporation. All rights reserved.
g++ -c -g -frtti -fexceptions -mthreads -Wall -DUNICODE -DQT_LARGEFILE_S
UPPORT -DQT_DLL -DQT_GUI_LIB -DQT_CORE_LIB -DQT_THREAD_SUPPORT -DQT_NEEDS_QMAIN
-I'../../../include/QtCore' -I'../../../include/QtCore' -I'../../../include/QtGu
i' -I'../../../include/QtGui' -I'../../../include' -I'.' -I'd:/Qt/4.4.0/include/
ActiveQt' -I'tmp/moc/debug_shared' -I'.' -I'../../../mkspecs/win32-g++' -o tmp/o
bj/debug_shared/dialog.o dialog.cpp
dialog.cpp:44:17: QtGui: No such file or directory
In file included from dialog.cpp:46:
dialog.h:47:19: QDialog: No such file or directory
In file included from dialog.cpp:46:
dialog.h:51: error: expected class-name before '{' token
dialog.h:54: error: ISO C++ forbids declaration of `Q_OBJECT' with no type
dialog.h:54: error: expected `;' before "public"
dialog.h:59: error: `QRect' does not name a type
dialog.h:61: error: expected `:' before "slots"
dialog.h:62: error: expected primary-expression before "void"
dialog.h:62: error: ISO C++ forbids declaration of `slots' with no type
dialog.h:62: error: expected `;' before "void"
dialog.cpp:50: error: definition of implicitly-declared `Dialog::Dialog()'
dialog.cpp:50: error: declaration of `Dialog::Dialog()' throws different excepti
ons
dialog.h:51: error: than previous declaration `Dialog::Dialog() throw ()'
dialog.cpp: In constructor `Dialog::Dialog()':
dialog.cpp:51: error: `desktopGeometry' was not declared in this scope
dialog.cpp:51: error: `QApplication' has not been declared
dialog.cpp:51: error: `desktop' was not declared in this scope
dialog.cpp:53: error: `tr' was not declared in this scope
dialog.cpp:53: error: `setWindowTitle' was not declared in this scope
dialog.cpp:54: error: `QScrollArea' was not declared in this scope
dialog.cpp:54: error: `scrollArea' was not declared in this scope
dialog.cpp:54: error: `QScrollArea' is not a type
dialog.cpp:55: error: `QGroupBox' was not declared in this scope
dialog.cpp:55: error: `groupBox' was not declared in this scope
dialog.cpp:55: error: `QGroupBox' is not a type
dialog.cpp:57: error: `QGridLayout' was not declared in this scope
dialog.cpp:57: error: `gridLayout' was not declared in this scope
dialog.cpp:57: error: `QGridLayout' is not a type
dialog.cpp:62: error: `QLineEdit' was not declared in this scope
dialog.cpp:62: error: `lineEdit' was not declared in this scope
dialog.cpp:62: error: `QLineEdit' is not a type
dialog.cpp:66: error: `QLabel' was not declared in this scope
dialog.cpp:66: error: `label' was not declared in this scope
dialog.cpp:66: error: `QLabel' is not a type
dialog.cpp:70: error: `QPushButton' was not declared in this scope
dialog.cpp:70: error: `button' was not declared in this scope
dialog.cpp:70: error: `QPushButton' is not a type
dialog.cpp:88: error: `QHBoxLayout' was not declared in this scope
dialog.cpp:88: error: `layout' was not declared in this scope
dialog.cpp:88: error: `QHBoxLayout' is not a type
dialog.cpp:90: error: `setLayout' was not declared in this scope
dialog.cpp:91: error: `Qt' has not been declared
dialog.cpp:91: error: `ScrollBarAlwaysOff' was not declared in this scope
dialog.cpp:95: error: `pressed' was not declared in this scope
dialog.cpp:95: error: `SIGNAL' was not declared in this scope
dialog.cpp:96: error: `qApp' was not declared in this scope
dialog.cpp:96: error: `closeAllWindows' was not declared in this scope
dialog.cpp:96: error: `SLOT' was not declared in this scope
dialog.cpp:96: error: `connect' was not declared in this scope
dialog.cpp:97: error: `QApplication' has not been declared
dialog.cpp:97: error: expected primary-expression before "int"
dialog.cpp:97: error: `workAreaResized' was not declared in this scope
dialog.cpp:98: error: expected primary-expression before "int"
dialog.cpp:98: error: `desktopResized' was not declared in this scope
dialog.cpp:53: warning: unused variable 'setWindowTitle'
dialog.cpp:54: warning: unused variable 'QScrollArea'
dialog.cpp:55: warning: unused variable 'QGroupBox'
dialog.cpp:57: warning: unused variable 'QGridLayout'
dialog.cpp:62: warning: unused variable 'QLineEdit'
dialog.cpp:66: warning: unused variable 'QLabel'
dialog.cpp:70: warning: unused variable 'QPushButton'
dialog.cpp:88: warning: unused variable 'QHBoxLayout'
dialog.cpp:90: warning: unused variable 'setLayout'
dialog.cpp:91: warning: unused variable 'ScrollBarAlwaysOff'
dialog.cpp:95: warning: unused variable 'pressed'
dialog.cpp:96: warning: unused variable 'qApp'
dialog.cpp:96: warning: unused variable 'closeAllWindows'
dialog.cpp:97: warning: unused variable 'workAreaResized'
dialog.cpp:98: warning: unused variable 'desktopResized'
dialog.cpp: At global scope:
dialog.cpp:104: error: no `void Dialog::desktopResized(int)' member function dec
lared in class `Dialog'
dialog.cpp: In member function `void Dialog::reactToSIP()':
dialog.cpp:114: error: `QRect' was not declared in this scope
dialog.cpp:114: error: expected `;' before "availableGeometry"
dialog.cpp:116: error: `desktopGeometry' was not declared in this scope
dialog.cpp:116: error: `availableGeometry' was not declared in this scope
dialog.cpp:118: error: `windowState' was not declared in this scope
dialog.cpp:118: error: `Qt' has not been declared
dialog.cpp:118: error: `WindowMaximized' was not declared in this scope
dialog.cpp:118: error: `setWindowState' was not declared in this scope
dialog.cpp:119: error: `setGeometry' was not declared in this scope
dialog.cpp:118: warning: unused variable 'windowState'
dialog.cpp:118: warning: unused variable 'WindowMaximized'
dialog.cpp:118: warning: unused variable 'setWindowState'
dialog.cpp:119: warning: unused variable 'setGeometry'
dialog.cpp:121: error: `windowState' was not declared in this scope
dialog.cpp:121: error: `Qt' has not been declared
dialog.cpp:121: error: `WindowMaximized' was not declared in this scope
dialog.cpp:121: error: `setWindowState' was not declared in this scope
dialog.cpp:121: warning: unused variable 'windowState'
dialog.cpp:121: warning: unused variable 'WindowMaximized'
dialog.cpp:121: warning: unused variable 'setWindowState'
dialog.cpp:124: error: `desktopGeometry' was not declared in this scope
dialog.cpp:124: error: `availableGeometry' was not declared in this scope
dialog.cpp:114: warning: unused variable 'QRect'
dialog.cpp:124: warning: unused variable 'desktopGeometry'
dialog.cpp:124: warning: unused variable 'availableGeometry'
NMAKE : fatal error U1077: 'C:MinGWbing++.EXE' : return code '0x1'
Stop.
NMAKE : fatal error U1077: '"C:ProgrammiMicrosoft Visual Studio 9.0VCBINnma
ke.exe"' : return code '0x2'
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
