ERROR C2143: Syntax error: missing ';' before '<' C++ - c++

I am having trouble in my C++ code where I have to make a binary heap. It works fine as long as I had the "main" function inside of my "MyHeap.h" file but my professor wants it to run in a separate test file. For some reason the code doesn't want to run whenever I try to put the main function outside of the "MyHeap.h" file. When it runs I get the following error:
error C2143: syntax error: missing';' before '<'
I looked at my code and this is where it says there is an error but I can't see anything.
// MyHeap.h
#ifndef _MYHEAP_H
#define _MYHEAP_H
#include <vector>
#include <iterator>
#include <iostream>
class Heap {
public:
Heap();
~Heap();
void insert(int element);
int deletemax();
void print();
int size() { return heap.size(); }
private:
int left(int parent);
int right(int parent);
int parent(int child);
void heapifyup(int index);
void heapifydown(int index);
private:
vector<int> heap;
};
#endif // _MYHEAP_H
So like I said whenever I have the the int main function right after the private class, it will work just fine. Now when I implement it into my test file which is this:
#include "MyHeap.h"
#include <vector>
#include <iostream>
int main()
{
// Create the heap
Heap* myheap = new Heap();
myheap->insert(25);
myheap->print();
myheap->insert(75);
myheap->print();
myheap->insert(100);
myheap->print();
myheap->deletemax();
myheap->print();
myheap->insert(500);
myheap->print();
return 0;
}
It keeps popping up the errors, any ideas on I could go about fixing this problem so that my code can run from a test file?

Use std::vector instead of vector.
The compiler is complaining it doesn't know about vector.
Since it lives in std namespace, the safest solution is to prefix with std.

Related

C++.Passing to functions.Syntax issue

I am pursuing some interest in c++ programming by way of self instruction. I am working on some basic stuff for now and am currently having issue getting my classes talking/instantiated?.
I am trying to get my main cpp file to compile alongside a header and call to some class functions through the main using a more efficient command method.
I am stuck and would appreciate some help. I will include both files. I am just trying to get a return value from the header by calling the function.
error:
main.cpp:6.21 error: cannot call member function 'void myClass::setNumber(int) without object
the code works when compiled with the main, so it is something with the 'scope resolution operator' i think. First is main.cpp
#include <iostream>
#include "myClass.h"
using namespace std;
int main(){
myClass::setNumber(6);
{
return number;
}
}
Then my header file myClass.h
// MyClass.h
#ifndef MYCLASS_H
#define MYCLASS_H
class myClass {
private:
int number;//declares the int 'number'
float numberFloat;//declares the float 'numberFloat
public:
void setNumber(int x) {
number = x;//wraps the argument "x" as "number"
}
void setNumberFloat(float x) {
numberFloat = x;
}
int getNumber() {//defines the function within the class.
number += 500;
return number;
}
float getNumberFloat() {//defines the function
numberFloat *= 1.07;
return numberFloat;
}
};
#endif
Any help?
The error message says everything:
cannot call member function 'void myClass::setNumber(int)' without object
You need to create an object first:
myClass obj;
then call the class method on that object:
obj.setNumber(6);
The value 6 will get assigned to the number field of the obj variable.

Accessing Methods in Declaration vs Implementation

I'm having difficulty interpreting some of my results, which I would expect to behave the same but are not.
I am trying to write a method that returns a function pointer getPtrFn
I have a main.c file reading
#include <iostream>
#include "test.hpp"
int main(int argc, char* argv[]){
Test test;
void (*fPtr)(void) = test.getPtrFn();
return 0;
}
A test.hpp file that reads
#ifndef _test_h
#define _test_h
class Test {
private:
void (*ptrFn)(void);
public:
Test(){};
void (*getPtrFn(void))(void){
return ptrFn;
};
~Test();
};
#endif
And a test.cpp file that reads
#include "test.hpp"
Test::~Test(){}
This runs fine. However, when I move the implementation for *getPtrFn(void) to the implementation file (revised files shown below),
test.hpp:
#ifndef _test_h
#define _test_h
class Test {
private:
void (*ptrFn)(void);
public:
Test(){};
void (*getPtrFn(void))(void);
~Test();
};
#endif
test.cpp:
#include "test.hpp"
void (Test::*getPtrFn)(void){
return ptrFn;
};
Test::~Test(){}
I get the compile error
test.cpp:16:9: error: use of undeclared identifier 'ptrFn'
My understanding of the language syntax is that they would be treated the same. So what gives?
-Jeff
You need
void(*Test::getPtrFn(void))(void)
{
return ptrFn;
}
instead of void (Test::*getPtrFn)(void){...}. void (Test::*getPtrFn)(void) is the declaration of getPtrFn as a pointer-to-Test-member-function taking no parameters (void) and returning void, so after you put the braces { ... } you get a compile-time error (its like trying to declare int i{/*some statemets*/}).
Also, and don't forget to keep the declaration
void(*getPtrFn(void))(void);
in your header (right now it seems you don't have it, did you cut/pasted it?).
Quite a horrible thing to look at... So really, use a type alias, it makes your code much cleaner.
using PTRFN = void(*)(void); // or typedef void(*PTRFN)(void);
class Test {
private:
PTRFN ptrFn;
public:
PTRFN getPtrFn(void);
Test(){};
~Test(){};
};
PTRFN Test::getPtrFn(void) // clear an concise
{
return ptrFn;
}
In case you really really want to be able do decipher every kind of pointer declaration you can think of, try looking at the clockwise/spiral rule, I found it extremely useful, clear and easy to understand. Then test your knowledge at cdecl.org.

undeclared identifier

Need a second set of eyes. I am getting the following error:
1>c:\users\thom\documents\cworkspace\barnaby\barnaby\timezone.h(15): error C2065: 'TransitionTimeInfo' : undeclared identifier
Here is the line of code on which I'm receiving the error:
Timezone(std::vector<LeapSecondsInfo> &leapSecondsVector, std::vector<unsigned char> &localTimeTypes, std::vector<P6::UINT8> &stdWallIndicators, &std::vector<unsigned long> &transitionTimes, std::vector<TransitionTimeInfo> &transitionTimesInfo, std::vector<P6::UINT8> &utcLocalIndicators){
This is the line for the constructor for my class. This file has the following include:
#include "stdafx.h"
And here is the salient part of the stdafx.h:
#include "targetver.h"
#include "barnaby.h"
#include "LeapSecondsInfo.h"
#include "p6types.h"
#include "Timezone.h"
#include "TransitionTimeInfo.h"
And here is TransitionTimeInfo.h:
class TransitionTimeInfo
{
public:
TransitionTimeInfo(long gmtOffset, bool daylightSavings, unsigned int abbreviationIndex){
setAbbreviationIndex(abbreviationIndex);
setDaylightSavings(daylightSavings);
setGmtOffset(gmtOffset);
}
virtual ~TransitionTimeInfo(void) {};
unsigned int getAbbreviationIndex(){
return abbreviationIndex;
}
void setAbbreviationIndex(unsigned int newVal){
abbreviationIndex = newVal;
}
bool isDaylightSavings(){
return daylightSavings;
}
void setDaylightSavings(bool newVal){
daylightSavings = newVal;
}
long getGmtOffset(){
return gmtOffset;
}
void setGmtOffset(long newVal){
gmtOffset = newVal;
}
private:
long gmtOffset;
bool daylightSavings;
unsigned int abbreviationIndex;
};
What's more, if I click on the type name and hit F12 (Visual C++) it takes me to this file.
Any ideas?
Thanks.
Change the order of includes:
#include "TransitionTimeInfo.h"
#include "Timezone.h"
The Timezone.h uses TransitionTimeInfo but the "TransitionTimeInfo.h" is included after it.
Ideally, You should always follow the rule:
Each file should include all the header files it needs and not rely on them getting included indirectly through some other files.
So, You should include "TransitionTimeInfo.h" in "Timezone.h".

Syntax error: Array of Vectors in OO C++

I've got an outline of a HashTable class I'm trying to make. I'm getting 3 errors output from Visual Studio, but I can't see the problem here. I'm fairly new to OO in C++ so it's probably something i've missed. It claims there is a problem with my array of vectors. The errors are:
error C2143: syntax error : missing ';' before '<' line 10
error C2238: unexpected token(s) preceding ';' line 10
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int line 10
Here's my complete class, it's pretty empty right now:
#include <iostream>
#include <vector>
#include "stdafx.h"
using namespace std;
class HashTable
{
private:
const static int buckets = 100;
vector<int> hashTable[buckets]; //Internal storage
int hash(int toHash); //Performs hash function
public:
HashTable(); //Constructor
HashTable(int s); //Constructor
~HashTable(); //Destructor
void add(int toAdd); //Adds an element to the HashTable
void remove(int toDelete); //Deletes an element from the HashTable
bool search(int toSearch); //Returns true if element in HashTable, false otherwise
int getSize(); //Returns size of HashTable
void print(); //Prints current state of the hashtable
//TODO more methods...?
};
//Definitions...
HashTable::HashTable()
{
}
HashTable::~HashTable()
{
//cout << "Destroyed" << endl;
}
void HashTable::add(int toAdd)
{
//elements[hash(toAdd)] = toAdd;
}
void HashTable::remove(int toDelete)
{
}
bool HashTable::search(int toSearch)
{
}
int HashTable::getSize()
{
//return size;
}
void HashTable::print()
{
}
int main()
{
return 0;
}
The C++ here is valid (once you fill in the empty functions). The problem is with how Visual C++ uses precompiled headers. When you use precompiled headers (the default setting), the Visual C++ compiler expects the first line of each implementation file to be #include "stdafx.h", and doesn't compile anything that appears before that.
This means the the include of <vector> in your code is ignored, and thus compiling vector<int> causes an error.
If you move the line #include "stdafx.h" to the top this should compile. Or you can disable precompiled headers in the project settings.

Help with error: ISO C++ forbids declaration of 'vector' with no type

As the title states, I'm not sure why I'm getting this error. I've put together a test.cpp that's similar to this structure, and it works fine. Also, other than the vector problem, there's the other problem about 'protected', which isn't even in the code. I think 'protected' is a macro, so no telling what's there. I'm new to QT, so I'm likely "doing it wrong." That's certainly what the compiler's suggesting.
In file included from DrvCrystalfontz.cpp:8:
LCDText.h:28: error: ISO C++ forbids declaration of 'vector' with no type
LCDText.h:28: error: expected ';' before '<' token
LCDText.h:30: error: ISO C++ forbids declaration of 'vector' with no type
LCDText.h:30: error: expected ',' or '...' before '<' token
LCDText.h:46: error: expected ':' before 'protected'
LCDText.h: In constructor 'LCDText::LCDText(int, int, int, int, int, int, int, QObject*)':
LCDText.h:33: error: expected '{' at end of input
scons: *** [DrvCrystalfontz.o] Error 1
scons: building terminated because of errors.
Here's the code. I've numbered the lines noted in the error.
#ifndef __LCD_TEXT__
#define __LCD_TEXT__
#include <vector>
#include <QObject>
#include "LCDBase.h"
#include "WidgetText.h"
#include "WidgetBar.h"
#include "WidgetHistogram.h"
#include "WidgetIcon.h"
#include "WidgetBignums.h"
#include "WidgetGif.h"
class LCDText: public LCDBase, public virtual QObject {
Q_OBJECT
protected:
char *LayoutFB;
char *DisplayFB;
int GOTO_COST;
int CHARS;
int CHAR0;
int LROWS;
int LCOLS;
int DROWS;
int DCOLS;
vector<vector<char *> > chars; // Line 28
void (*TextRealWrite) (const int row, const int col, const char *data, const int len);
void (*TextRealDefchar) (const int ascii, const vector<char *> matrix); // Line 30
public:
LCDText(int rows, int cols, int xres, int yres, int _goto, int chars,
int char0, QObject *parent) : LCDBase(xres, yres), QObject(parent); // Line 33
~LCDText();
void TextInit(int rows, int cols);
void TextBlit(int row, int col, int height, int width);
void TextClear();
void TextClearChars();
void TextGreet();
void TextDraw(WidgetText widget);
void TextBarDraw(WidgetBar widget);
void TextHistogramDraw(WidgetHistogram widget);
void TextIconDraw(WidgetIcon widget);
void TextBignumsDraw(WidgetBignums widget);
void TextGifDraw(WidgetGif widget);
public signals: // Line 46
void SpecialCharChanged(int ch);
public slots:
void TextSpecialCharChanged(int ch);
};
#endif
Vector resides in the std namespace. You have to do one of the following:
Prepend the type with the namespace:
std::vector<std::vector<char *> > chars;
Tell the compiler you are using vector from the std namespace
using std::vector;
vector<vector<char *> > chars;
Or, tell the compiler you are using the std namespace, which will bring in everything (not recommended, see comments)
using namespace std;
every symbol declared in C++ standard library is part of the std namespace. In order to use these declarations you have to refer it by its full name. namely std::.
As MichaelM answered you should use std::vector instead of vector.
You can, however, use the following "using declarations":
1. using std::vector;
2. using namespace std; // using namespace ...; is mostly discouraged as it causes a mass-import of symbols into the global namespace
On any case, most of the time you should avoid using declaration in header files as it pollutes the global namespace for every user of your header.
good luck