I’m trying to compile my code to test a function to read and print a data file, but I get a compiling error that I don’t understand — «error: expected constructor, destructor, or type conversion before ‘;’ token». Wall of relevant code-text is below.
struct Day
{
int DayNum;
int TempMax;
int TempMin;
double Precip;
int TempRange;
};
struct Month
{
Day Days[31];
int MonthMaxTemp;
int MonthMinTemp;
double TotalPrecip;
int MonthMaxTempRange;
int MonthMinTempRange;
double AverageMaxTemp;
double AverageMinTemp;
int RainyDays;
double AveragePrecip;
}theMonth;
double GetMonth();
double GetMonth()
{
for (int Today = 1; Today < 31; Today++)
{
cout << theMonth.Days[Today].TempMax << theMonth.Days[Today].TempMin;
cout << theMonth.Days[Today].Precip;
}
return 0;
}
GetMonth(); // compile error reported here
asked Oct 15, 2009 at 15:36
1
The line with the error looks like you’re trying to call GetMonth — but at the global level, a C++ program consists of a series of declarations. Since a function call isn’t a declaration, it can’t exist in isolation at the global level. You can have a declaration that’s also a definition, in which case it can invoke a function as part of initialization.
A function call by itself, however, has to be contained within some other function:
#ifdef TEST
int main() {
GetMonth();
}
#endif
answered Oct 15, 2009 at 15:41
Jerry CoffinJerry Coffin
467k79 gold badges617 silver badges1097 bronze badges
1
(In addition to other replies.) In order to excute your ‘GetMonth()’ function you have to either call it from another function (‘main’ or whatever is called from ‘main’) or use it in initializer expression of an object declared at namespace scope, as in
double global_dummy = GetMonth();
However, the latter method might suffer from initialization order problems, which is why it is recommended to use the former method whenever possible.
answered Oct 15, 2009 at 16:03
0
In C/C++, you cannot simply add executable code into the body of a header or implementation (.c,.cpp,.cxx,etc…) file. Instead you must add it to a function. If you want to have the code run on startup, make sure to add it to the main method.
int main(int argc, char *argv[]) {
GetMonth();
}
answered Oct 15, 2009 at 15:41
JaredParJaredPar
722k147 gold badges1226 silver badges1449 bronze badges
C++ programs don’t execute in a global context. This means you need to put the call to GetMonth into a function for it to run. int main() { }
might be appropriate.
answered Oct 15, 2009 at 15:43
Andres Jaan TackAndres Jaan Tack
22.3k10 gold badges59 silver badges77 bronze badges
Compiling polygone.h
and polygone.cc
gives error:
polygone.cc:5:19: error: expected constructor, destructor, or type conversion before ‘(’ token
Code:
//polygone.h
# if !defined(__POLYGONE_H__)
# define __POLYGONE_H__
# include <iostream>
class Polygone {
public:
Polygone(){};
Polygone(std::string fichier);
};
# endif
and
//polygone.cc
# include <iostream>
# include <fstream>
# include "polygone.h"
Polygone::Polygone(string nom)
{
std::ifstream fichier (nom, ios::in);
std::string line;
if (fichier.is_open())
{
while ( fichier.good() )
{
getline (fichier, line);
std::cout << line << std::endl;
}
}
else
{
std::cerr << "Erreur a l'ouverture du fichier" << std::endl;
}
}
//ifstream fich1 (argv[1], ios::in);
My guess is that the compiler is not recognising Polygone::Polygone(string nom)
as a constructor, but, if this actually is the case, I have no idea why.
Any help?
asked Jan 22, 2012 at 0:42
2
This is not only a ‘newbie’ scenario. I just ran across this compiler message (GCC 5.4) when refactoring a class to remove some constructor parameters. I forgot to update both the declaration and definition, and the compiler spit out this unintuitive error.
The bottom line seems to be this: If the compiler can’t match the definition’s signature to the declaration’s signature it thinks the definition is not a constructor and then doesn’t know how to parse the code and displays this error. Which is also what happened for the OP: std::string
is not the same type as string
so the declaration’s signature differed from the definition’s and this message was spit out.
As a side note, it would be nice if the compiler looked for almost-matching constructor signatures and upon finding one suggested that the parameters didn’t match rather than giving this message.
answered Jan 25, 2019 at 22:16
Bob KociskoBob Kocisko
5441 gold badge7 silver badges14 bronze badges
The first constructor in the header should not end with a semicolon. #include <string>
is missing in the header. string
is not qualified with std::
in the .cpp file. Those are all simple syntax errors. More importantly: you are not using references, when you should. Also the way you use the ifstream
is broken. I suggest learning C++ before trying to use it.
Let’s fix this up:
//polygone.h
# if !defined(__POLYGONE_H__)
# define __POLYGONE_H__
#include <iostream>
#include <string>
class Polygone {
public:
// declarations have to end with a semicolon, definitions do not
Polygone(){} // why would we needs this?
Polygone(const std::string& fichier);
};
# endif
and
//polygone.cc
// no need to include things twice
#include "polygone.h"
#include <fstream>
Polygone::Polygone(const std::string& nom)
{
std::ifstream fichier (nom, ios::in);
if (fichier.is_open())
{
// keep the scope as tiny as possible
std::string line;
// getline returns the stream and streams convert to booleans
while ( std::getline(fichier, line) )
{
std::cout << line << std::endl;
}
}
else
{
std::cerr << "Erreur a l'ouverture du fichier" << std::endl;
}
}
answered Jan 22, 2012 at 0:47
pmrpmr
57.8k10 gold badges110 silver badges155 bronze badges
5
You are missing the std namespace reference in the cc file. You should also call nom.c_str()
because there is no implicit conversion from std::string
to const char *
expected by ifstream
‘s constructor.
Polygone::Polygone(std::string nom) {
std::ifstream fichier (nom.c_str(), std::ifstream::in);
// ...
}
answered Jan 22, 2012 at 0:50
You need the return type, for example «void Polygon…»
answered Nov 10, 2021 at 16:32
2
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 |
#include <iostream> #include <cstdlib> #include <string.h> #include <stdio.h> #include <iomanip> #include <conio.h> #define N 3 using std::cin; using std::cout; using std::endl; class prisList { char *naimenovanie; char tipTovara; float cena; int min; public: void set (char *m, char j, float k, int c); void get (char *m, char &j, float &k, int &c); void show (void); }; void prisList::set (char *m, char j, float k, int c) { strcpy(naimenovanie,m); tipTovara=j; cena=k; min=c; } void prisList::get (char *m , char &j, float &k, int &c) { delete[] m; m=new char [strlen(naimenovanie)+1]; strcpy(m,naimenovanie); j=tipTovara; k=cena; c=min; } void prisList::show(void) { cout<<naimenovanie<<" "; cout<<tipTovara<<" "; cout<<cena<<" "; cout<<min<<" "; } int main() { char *a; char b; float f; float d; short p; } prisList obj[N]; clrscr(); std::cout<<"F-ya SET n"<<endl; for (p=0; p < N; p++) { cout<<"NaimenovanieTovara, tipTovara, cenaZa1Shtyky, minColichestvoVPartii: "<<endl; cin>>a; cin>>b; cin>>f; cin>>d; obj[p].set(a,b,f,d); } cout<<"f-ya SHOW"<<endl; cout<<"NaimenovanieTovara, tipTovara, cenaZa1Shtyky, minColichestvoVPartii: "<<endl; for (p=0; p < N; p++) { obj[p].show(); cout<<"n"; } cout<<"f-ii GET i SHOW"<<endl; cout<<"NaimenovanieTovara, tipTovara, cenaZa1Shtyky, minColichestvoVPartii: "<<endl; for (p=0; p < N; p++) { obj[p].set(a,b,f,d); obj[p].show(); cout<<"n"; } system("PAUSE"); delete[] a; return 0; } |
Hi.. I have tried the below code and it is giving compilation error as ‘error: expected constructor, destructor, or type conversion before ‘;’ token. Please suggest for this error.
|
|
Please suggest what is wrong in above code.
/*
Two 28BYJ-48 5V Stepper motors controlled by HC-SR04 Sonar module
*/
//—————————Stepper motor globals————————
#include <AccelStepper.h>
// Define Constants
//distance x 3.3 = speed
const int speedFacter = 3.3;
// Define step constants
int maxSpeed = 200;
int lowSpeed = 50;
#define FULLSTEP 4
#define HALFSTEP 8
// define variables
long stepSpeed1 = maxSpeed;
long stepSpeed2 = maxSpeed;
unsigned long startTime;
unsigned long elapsedTime;
// Define Motor Pins (2 Motors used)
#define motorPin1 8 // Blue — 28BYJ48 pin 1
#define motorPin2 9 // Pink — 28BYJ48 pin 2
#define motorPin3 10 // Yellow — 28BYJ48 pin 3
#define motorPin4 11 // Orange — 28BYJ48 pin 4
#define motorPin5 4 // Blue — 28BYJ48 pin 1
#define motorPin6 5 // Pink — 28BYJ48 pin 2
#define motorPin7 6 // Yellow — 28BYJ48 pin 3
#define motorPin8 7 // Orange — 28BYJ48 pin 4
// Define two motor objects
// The sequence 1-3-2-4 is required for proper sequencing of 28BYJ48
AccelStepper stepper1(HALFSTEP, motorPin1, motorPin3, motorPin2, motorPin4);
// AccelStepper stepper2(FULLSTEP, motorPin5, motorPin7, motorPin6, motorPin8);
AccelStepper stepper2(HALFSTEP, motorPin5, motorPin7, motorPin6, motorPin8);
//—————————Sonar-HC-SR04 globals——————————————
// Hook up HC-SR04 with Trig to Arduino Pin 10, Echo to Arduino pin 13
// Maximum Distance is 400 cm
// Include the AccelStepper Library
// Include NewPing Library
#include «NewPing.h»
#define TRIGGER_PIN 12
#define ECHO_PIN 13
#define MAX_DISTANCE 400
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
float distance;
//————————————————————————-
void setup()
// stepper setup
{
// 1 revolution Motor 1 CW
stepper1.setMaxSpeed(1000.0);
stepper1.setAcceleration(50.0);
stepper1.setSpeed(stepSpeed1);
stepper1.moveTo(2048);
// 1 revolution Motor 2 CCW
stepper2.setMaxSpeed(1000.0);
stepper2.setAcceleration(50.0);
stepper2.setSpeed(stepSpeed2);
stepper2.moveTo(—2048);
//————————-Sonar setup————————————
// define pins 14, 15 and 16 for LED distance indicators
for (int i = 14; i < 17; i++) {
pinMode (i,OUTPUT);
}
}
//define function to turn LED’s off
void alloff(void) {
for (int i = 14; i < 17; i++){
digitalWrite (14,LOW);
}
}
//define function to turn LED’s on
void allon(void) {
for (int i = 14; i < 17; i++){
digitalWrite (14,HIGH);
}
}
//define function to Change direction at the limits
void changDirection(void) {
if (stepper1.distanceToGo() == 0)
stepper1.moveTo(—stepper1.currentPosition());
if (stepper2.distanceToGo() == 0)
stepper2.moveTo(—stepper2.currentPosition());
}
// function to change speed
newSpeed (stepSpeed1, stepSpeed2)
{
stepper1.setSpeed(stepSpeed1);
stepper2.setSpeed(stepSpeed2);
}
// =============================================
void loop()
{
distance = sonar.ping_cm();
int (d) = distance;
switch (d){
//change direction
case 2 … 4:
alloff;
allon;
digitalWrite (14,HIGH);
digitalWrite (15,HIGH);
changDirection();
break;
case 5 … 10:
alloff;
digitalWrite(14,HIGH);
alloff();
digitalWrite(14, HIGH);
stepSpeed1 = lowSpeed;
stepSpeed2 = lowSpeed;
//newSpeed (stepSpeed1, stepSpeed2);
break;
case 11 … 15:
alloff();
digitalWrite(15, HIGH);
stepSpeed1 = maxSpeed/2;
stepSpeed2 = maxSpeed/2;
//newSpeed (stepSpeed1, stepSpeed2);
break;
case 16 … 20:
alloff();
digitalWrite(16, HIGH);
stepSpeed1 = maxSpeed;
stepSpeed2 = maxSpeed;
//newSpeed (stepSpeed1, stepSpeed2);
break;
//change stepper1 direction and speed
case 21 … 30:
alloff();
allon ();
delay (1000);
alloff();
delay (1000);
allon ();
break;
case 31 … 60:
// change speed with a conversion facter
stepSpeed1 = speedFacter * d;
stepSpeed2 = speedFacter * d;
alloff();
allon ();
default:
break;
}
/*Change direction at the limits
if (stepper1.distanceToGo() == 0)
stepper1.moveTo(-stepper1.currentPosition());
if (stepper2.distanceToGo() == 0)
stepper2.moveTo(-stepper2.currentPosition());
*/
stepper1.run();
stepper2.run();
}
Recommended Answers
You include stack.cpp before and after template definition
Jump to Post
The problem may be that the compiler sees a possibility of your .cpp file attempt to define something that doesn’t exist, since your header file is conditionally defined.
You can make it, such that, the text in your implementation file is read by the compiler if and only if …
Jump to Post
VC++ 2008 compiles this template w/o errors. Of course, I define dummy linklist template with get_head() to link test executable.
What compiler are you using?It was not the best idea to call your own class «stack»: it’s a name of STL class. It’s not an error, but better …
Jump to Post
All 11 Replies
14 Years Ago
Here is complete list of Error…
stack.cpp:1: error: expected constructor, destructor, or type conversion before ‘<‘ token
stack.cpp:9: error: expected constructor, destructor, or type conversion before ‘<‘ token
stack.cpp:15: error: expected initializer before ‘<‘ token
stack.cpp:25: error: expected initializer before ‘<‘ token
stack.cpp:39: error: expected initializer before ‘<‘ token
stack.cpp:55: error: expected initializer before ‘<‘ to
I have adjusted the line Numbering respectively.
ArkM
1,090
Postaholic
14 Years Ago
You include stack.cpp before and after template definition
14 Years Ago
Sorry thats by mistake..
No help after even removing one of them.
No difference either I place
#include "stack.cpp"
at the end of file or in the begining.
14 Years Ago
The problem may be that the compiler sees a possibility of your .cpp file attempt to define something that doesn’t exist, since your header file is conditionally defined.
You can make it, such that, the text in your implementation file is read by the compiler if and only if the header is defined—
#ifdef STACK_H
template <class T> stack<T>::stack()
{
}
template <class T> stack<T>::~stack()
{
}
template <class T> void stack<T>::push(T c)
{
lst.Insert(c) ;
}
template <class T> T stack<T>::pop()
{
T c = lst.get_head_suffix() ;
lst.Remove() ;
return c ;
}
template <class T> bool stack<T>::is_empty()
{
if (lst.get_head() == 0)
return true ;
else
return false ;
}
template <class T> T stack<T>::peek()
{
if (!is_empty())
{
T c = lst.get_head_suffix() ;
return c ;
}
}
#endif
— you are not the only one with this problem. Apparently when using eager-inclusion, the implementation file must be restricted.
-Alex
Note: Hopefully you are also only including your Stack.h header file and not the .cpp file with it (since its already being included via eager inclusion).
ArkM
1,090
Postaholic
14 Years Ago
VC++ 2008 compiles this template w/o errors. Of course, I define dummy linklist template with get_head() to link test executable.
What compiler are you using?
It was not the best idea to call your own class «stack»: it’s a name of STL class. It’s not an error, but better use Stack name or what else. Common convention: user class names are capitalized…
14 Years Ago
Remove
‘#include «stack.cpp»‘ at stack.h file..
Add
‘#include «stack.h»‘
to your stack.cpp file..
14 Years Ago
Remove
‘#include «stack.cpp»‘ at stack.h file..
Add
‘#include «stack.h»‘
to your stack.cpp file..
According to my readings, it is different for Templated class (FAQLITE.com mentions it and ask to use EXPORT keyword, but GCC, VCC doesn’t implement export now.
So I included *.cpp in *.h instead of including *.h in .cpp.
If I follow the standard approach mentioned by you then the error is:
I have written following in main()
int main()
{
Stack<char> s1 ;
char s[4] ;
s1.push('S') ;
s1.push('A') ;
s1.push('A') ;
s1.push('Z') ;
for (int i = 0 ; i<4; i++)
s[i] = s1.pop() ;
for (int i = 3 ; i>=0; i--)
cout<<s[i]<<" " ;
cout << "Hello world!" << endl;
return 0;
}
The Error is as follows.
undefined reference to `Stack<char>::Stack()’|
undefined reference to `Stack<char>::push(char)’
undefined reference to `Stack<char>::push(char)’
undefined reference to `Stack<char>::push(char)’
undefined reference to `Stack<char>::push(char)’
undefined reference to `Stack<char>::pop()’|
undefined reference to `Stack<char>::~Stack()’
||=== Build finished: 8 errors, 0 warnings ===|
VC++ 2008 compiles this template w/o errors. Of course, I define dummy linklist template with get_head() to link test executable.
What compiler are you using?
GCC… TEsted on Dev Cpp and Code::Blocks on Vista. KDEVELOP on Opensuse Linux. same output.
My University requires compilation compatribility on GCC.
It was not the best idea to call your own class «stack»: it’s a name of STL class. It’s not an error, but better use Stack name or what else. Common convention: user class names are capitalized…
Changed to Stack.. even removed using namespace std; but no luck .
14 Years Ago
HEre all contents of my project.
My project conatins 6 files, 3 .cpp and 3 .h
first the basic class node.h as unit of linkedlist.
#ifndef NODE_H
#define NODE_H
#include <iostream>
template <class T>
class node
{
public:
node();
~node();
node(T c, node *n = 0) ;
void set_suffix(T c) ;
T get_suffix() ;
void set_next(node<T> * n) ;
node<T>* get_next() ;
private:
T suffix;
node<T>* next;
};
#endif // NODE_H
Its Implementation.
#include "node.h"
#ifdef STACK_H
template <class T>
node<T>::node()
{
suffix = 0 ;
next = 0 ;
}
template <class T>
node<T>::node(T c, node *n)
{
suffix = c ;
next = n ;
}
template <class T>
node<T>::~node()
{
}
template <class T>
void node<T>::set_suffix(T c)
{
suffix = c ;
}
template <class T>
T node<T>::get_suffix()
{
return suffix ;
}
template <class T>
void node<T>::set_next(node<T> * n)
{
next = n ;
}
template <class T>
node<T>* node<T>::get_next()
{
return next ;
}
#endif
The LinkedList class Header.
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include "node.h"
template <class T>
class linkedlist
{
public:
linkedlist();
~linkedlist();
linkedlist(const linkedlist<T> & rhs) ;
linkedlist& operator = (const linkedlist<T>& rhs) ;
void delete_List() ;
void Insert(T c) ;
void Remove() ;
T get_head_suffix() ;
bool not_empty() ;
//void Display_List() ;
private:
node<T> * head ;
};
#endif // LINKEDLIST_H
Its Implementation.
#include "linkedlist.h"
#ifdef STACK_H
template <class T>
linkedlist<T>::linkedlist()
{
head = 0 ;
}
template <class T>
linkedlist<T>::linkedlist(const linkedlist<T> & rhs)
{
node<T>* temp = rhs.head, *temp2 = head, *prev_node ;
while (temp!= 0)
{
temp2 = new node<T>(temp2->get_suffix()) ;
if (head == 0)
{
head = temp2 ;
prev_node = head ;
}
else
{
prev_node->set_next(temp2) ;
prev_node = temp2 ;
}
temp = temp->get_next() ;
}
}
template <class T>
void linkedlist<T>::delete_List()
{
node<T> *temp = head, *temp2 = head ;
head = 0 ;
while(temp != 0)
{
temp = temp->get_next() ;
delete temp2 ;
temp2 = temp ;
}
}
template <class T>
linkedlist<T>::~linkedlist()
{
delete_List() ;
}
template <class T>
linkedlist<T>& linkedlist<T>::operator = (const linkedlist<T>& rhs)
{
if (this != &rhs)
{
node<T>* temp = rhs.head, *temp2 = head, *prev_node ;
while (temp!= 0)
{
temp2 = new node<T>(temp2->get_suffix()) ;
if (head == 0)
{
head = temp2 ;
prev_node = head ;
}
else
{
prev_node->set_next(temp2) ;
prev_node = temp2 ;
}
temp = temp->get_next() ;
}
}
return *this;
}
template <class T>
void linkedlist<T>::Insert(T c)
{
node<T>* temp ;
temp = new node<T>(c) ;
if (head == 0)
head = temp ;
else
{
temp->set_next(head) ;
head = temp ;
}
}
template <class T>
void linkedlist<T>::Remove()
{
if (head == 0)
return ;
node<T>* temp=head ;
head = temp->get_next() ;
delete temp ;
return ;
}
template <class T>
T linkedlist<T>::get_head_suffix()
{
return head->get_suffix() ;
}
template <class T>
bool linkedlist<T>::not_empty()
{
if (head == 0)
return true ;
else
return false ;
}
#endif
Stack CLass Header file..
#ifndef STACK_H
#define STACK_H
#include "linkedlist.h"
template <class T>
class Stack
{
public:
Stack();
~Stack();
void push(T c) ;
T pop() ;
bool is_empty() ;
T peek() ;
void display_Stack() ;
private:
linkedlist<T> lst ;
};
#endif
Stack CLass Implementation.
#include "stack.h"
#ifdef STACK_H
template <class T>
Stack<T>::Stack()
{
}
template <class T>
void Stack<T>::push(T c)
{
lst.Insert(c) ;
}
template <class T>
T Stack<T>::pop()
{
T c = lst.get_head_suffix() ;
lst.Remove() ;
return c ;
}
template <class T>
bool Stack<T>::is_empty()
{
if (lst.get_head() == 0)
return true ;
else
return false ;
}
template <class T>
T Stack<T>::peek()
{
if (!is_empty())
{
T c = lst.get_head_suffix() ;
return c ;
}
}
template <class T>
void Stack<T>::display_Stack()
{
lst.Display_List() ;
}
#endif
Included «stack.h» in ain and what I am doing in main I demonstrated it earlier..
Plz try ur best.. little days are remaining for the submission and I have to use this stack for Expression trees.. also would create a Queue class with same linkedlist to do Huffman Encoding and Decoding.
14 Years Ago
One thing more. If I implement the implementation as same in the declaration file and save it as .cpp and then include stack.cpp in my main it works…
ArkM
1,090
Postaholic
14 Years Ago
I have just compiled your original stack definition with MinGW compiler. It’s a gcc 4.3.0 port. All template stuff was placed in one file.
However your previous post presents useless version of the package. It’s impossible to compile Stack template specializations with stack.h header only.
Collect ALL Stack template stuff in stack.h (move member functions from stack.cpp to this file too) and try again.
Fujur
-2
Newbie Poster
13 Years Ago
Hello.
I had the same problem, and yes, if you copy your .cpp class specifications into the .h declaration the problem is solved.
An explanaition of why can be found here.
Good Luck.
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.