I am getting an error message saying the use of undeclared identifier 'IntQueue' in vscode and I cannot figure out what is wrong.
I have tried renaming the file but still does not work. I created a separate header file that has the class defined and I included the header file in the main cpp file that has all the constructors defined. But I cannot figure out a way to solve the issue.
//This is the IntQueue.h header file
#ifdef _IntQueue_
#define _IntQueue_
#include<iostream>
#include<fstream>
using namespace std;
class IntQueue {
int* numbers;
int size;
int front;
int back;
public:
IntQueue (unsigned int n);
IntQueue();
~IntQueue();
int getSize() {return size;}
int getFront() {return front;}
int getBack() {return back;}
void incSize();
void pop();
int frontNumber();
void push(int i);
void reverse();
};
#endif
//This is the IntQueue.cpp file (incomplete)
#include "IntQueue.h"
IntQueue::IntQueue (unsigned int n) {
size = n;
numbers = new int[size];
front = 0;
back = 0;
}
IntQueue::IntQueue() {
size = 100;
front = 0;
back = 0
numbers = new int [size];
}
You need to change
#ifdef _IntQueue_
To
#ifndef _IntQueue_
When your .cpp file #include's your .h file, _IntQueue_ has not been declared yet, so the #ifdef skips the entire content of the .h file, and so the compiler doesn't know anything about your IntQueue class.
Related
I'm making a heap class to be importable with heap.h and my constructors including bool types do not work, yet every other constructor and function imported works.
Here is what's in heap.h:
#ifndef __HEAP_INCLUDED__
#define __HEAP_INCLUDED__
#include <iostream>
#include <vector>
using namespace std;
class heap{
int capacity;
bool isMinHeap; //1 is min heap -- ascending order
vector<int> * content;
public:
heap();
heap(bool t);
heap(vector<int> * input);
heap(vector<int> * input, bool t);
void print();
void prettyPrint();
int parent(int i);
int leftChild(int i);
int rightChild(int i);
int size();
int getMax();
void insert(int data);
void heapifyDown(int index);
void heapifyUp(int index);
int invalidChild(int index);
int deleteMax();
int deleteMin();
bool minDir();
int at(int index);
};
vector<int> * heapSort(vector<int> * input);
void swap(vector<int> * vec, int a, int b);
#endif
Here are the defined constructors in heap.cpp. Note, all constructors work fine when I add a main to this file to test stuff:
class heap{
vector<int> * content;
int capacity = 256;
bool isMinHeap; //1 is min heap -- ascending order
public:
heap(){
content = new vector<int>;
isMinHeap = 0;
}
heap(bool t){
content = new vector<int>;
isMinHeap = t;
}
heap(vector<int> * input){
content = input;
isMinHeap = true;
for(int i = content->size()/2; i >= 0; i--){
heapifyDown(i);
}
}
heap(vector<int> * input, bool t){
content = input;
isMinHeap = t;
for(int i = content->size()/2; i >= 0; i--){
heapifyDown(i);
}
}
//other functions below
}
The constructors with bool do not work in main.cpp, which has #include "heap.h" at the top. The files are all in the same directory and I am compiling with this command: g++ heap.cpp main.cpp -o main. Why do two of my constructors not work?
The error I see is
/usr/bin/ld: /tmp/ccwomODk.o: in function `main':
main.cpp:(.text+0x4e2): undefined reference to `heap::heap(bool)'
collect2: error: ld returned 1 exit status
-Wall does not elaborate on the issue. I'm pretty sure the issue is with my linking somewhere because the constructors work inside of heap.cpp when I use them in there.
What you are doing with the class in the .cpp file is wrong. You are not allowed to define the class twice. There must only be one class heap { /*...*/ }; in the program (but it may be included in multiple .cpp files). Otherwise the one-definition-rule (ODR) is violated and the program has undefined behavior.
So remove everything you are showing from heap.cpp.
To define the constructors of heap in the heap.cpp file, you need to use this syntax:
#include "heap.h"
heap::heap() {
/*...*/
}
heap::heap(bool t) {
/*...*/
}
//...
and so on. The other member functions must be defined in a similar way, e.g.:
void heap::print() {
/*...*/
}
Furthermore, if you want to have a default member initializer as in
int capacity = 256;
add it in the declaration in the .h file instead.
I also want to add that having a pointer-to-std::vector as member is almost surely a wrong approach as well, but out-of-scope for the question.
When you declare a program element such as a class, function, or
variable, its name can only be "seen" and used in certain parts of
your program. The context in which a name is visible is called its
scope. For example, if you declare a variable x within a function, x
is only visible within that function body.
It seems you broke ODR rule so bad. Your class members including constructors has no body declared in the source file(heap.cpp).
Use '::' to make class members have a body:
//heap.cpp
"heap.h"
heap::heap()
{
}
heap:heap(vector<int> * input, bool t)
{
}
int heap::parent(int i)
{
return i;
}
// this is how you create a body for function that are class members
// the same should be done for all other functions
I am getting the error "error: Invalid use of AppleFarmer::AppleFarmer. I do not know why I am getting this error since I am not trying to pass any input into my Constructor. Is it possible I have an issue with my .h file? What am i doing wrong to get this error?
I have three different files, and I may also be having an issue with linking the code together as I am doing #include for a .cpp file. I am not sure if my code works aside from this error, but I am stuck on this error.
appleFarmerMain.cpp
#include<iostream>
#include "appleFarmer.cpp"
int main(){
AppleFarmer m;
int harvest;
int demand;
m.AppleFarmer();
while(m.endOfMonth()==false){
cout<<"Enter a harvest amount:"<<endl;
cin>>harvest;
m.harvestApples(harvest);
cout<<"Enter a demand:"<<endl;
cin>>demand;
m.sellApples(demand);
cout<<"Apple Inventory: "<<m.getInventory()<<endl;
m.updateCurrentDay();
}
return 0;
}
appleFarmer.cpp
#include "appleFarmer.h"
#include "<iostream>
using namespace std;
AppleFarmer::AppleFarmer(){
for(int i=0;i<30;i++){
sales[i]=0;
harvest[i]=0;
}
}
bool AppleFarmer::sellApples(int demand){
if(demand<= inventory){
sales[currentDay]=demand;
inventory=inventory-demand;
}
else{
sales[currentDay]=0;
}
}
void AppleFarmer::harvestApples(int dayHarvest){
harvest[currentDay]= dayHarvest;
inventory=inventory+dayHarvest;
}
bool AppleFarmer::endOfMonth(){
if (currentDay=maxDays){
return true;
}
else{
return false;
}
}
int AppleFarmer::updateCurrentDay(){
currentDay=currentDay+1;
}
int AppleFarmer::getInventory(){
return inventory;
}
double AppleFarmer::calculateAverageHarvest(){
}
double calculateAverageSales(){
}
void AppleFarmer::printSales(){
}
void AppleFarmer::printHarvest(){
}
appleFarmer.h
#ifndef APPLEFARMER_H
#define APPLEFARMER_H
class AppleFarmer
{
public:
AppleFarmer();
bool sellApples(int);
void harvestApples(int);
bool endOfMonth();
int updateCurrentDay();
int getInventory();
double calculateAverageHarvest();
double calculateAverageSales();
void printSales();
void printHarvest();
private:
int sales[30];
int harvest[30];
int maxDays = 30;
int currentDay = 0;
int inventory = 0;
};
#endif
In C++ you don't call the constructor on an object. That happens at object creation time. The line
m.AppleFarmer();
isn't needed. The constructor is implicitly called here:
AppleFarmer m;
You need to include appleFarmer.h instead of appleFarmer.cpp because the header file (with .h extension) contains the declaration while the .cpp file contains the implementation.
Then you need also to delete m.AppleFarmer(); because the constructor is called during the declaration (AppleFarmer m text line).
First post so take it easy on me :). I don't think I really need to put up any actual code for this, but let me know if I'm wrong. This is for a homework assignment in my college programming class. I am confused as to how to properly use my #include statements. Here is my file structure:
Header Files-->
header.h (Main header file, contains #include for various libraries, declares namespace, and provides my name and class info)
room.h (Blueprint for the room class)
ship.h (Blueprint for the ship class)
Source Files-->
main.cpp (Main Program)
functions.cpp (Functions for the main program)
room.cpp (Functions in the Room class)
ship.cpp (Functions in the Ship class)
Basically, my first instinct was to " #include "header.h" " in room.h, ship.h, main.cpp, and functions.cpp. Then " #include "ship.h" in ship.cpp, and " #include room.h " in room.cpp. However I began getting errors up the wazoo. I was having a similar problem during class but I had my teacher there to sort it out and I'm not exactly sure how we did it, and I also know that tons of errors usually indicates an include error.
Its annoying because I had it working somehow before I added the functions.cpp, but I really want to keep main.cpp pretty clean, so I would rather have functions in a separate file.
What is the best pattern for includes in a situation like this?
EDIT: I'll post my 3 header files
header.h
/*
Author: *********
Class : **********
Assignment : Programming Assignment 2
Description :
This program will construct a ship for the user. It accepts input from a file
containing information on various rooms. It will then check the rooms
validity and add it to the ship if it's valid. Once all of the rooms have been added,
the program will determine if the entire ship is valid and let the user know.
Certification of Authenticity :
I certify that this is entirely my own work, except where I have given
fully - documented references to the work of others.I understand the
definition and consequences of plagiarism and acknowledge that the assessor
of this assignment may, for the purpose of assessing this assignment :
-Reproduce this assignment and provide a copy to another member of
academic staff; and / or
- Communicate a copy of this assignment to a plagiarism checking
service(which may then retain a copy of this assignment on its
database for the purpose of future plagiarism checking)
*/
#ifndef header_h
#define header_h
#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;
#endif
room.h
#ifndef room_h
#define room_h
#include "header.h"
enum RoomType
{
UNKNOWN = -1,
BAY,
LATRINE,
CABIN,
BRIDGE,
NUM_ROOM_TYPES
};
const string ROOM_STRINGS[NUM_ROOM_TYPES] = { "Bay",
"Latrine",
"Cabin",
"Bridge"
};
class Room
{
public:
//default constructor
Room();
//constructor
Room( RoomType type, int width, int breadth, int height );
//destructor
~Room(){};
//accessors
inline RoomType getType() const { return mType; };
inline int getHeight() const { return mHeight; };
inline int getWidth() const { return mWidth; };
inline int getBreadth() const { return mBreadth; };
inline int getVolume() const { return getWidth() * getBreadth() * getHeight(); }; //currently unused
inline string getRoomName(){ return ROOM_STRINGS[mType]; };
string getDescription();
//mutators
void setType(RoomType type) {mType = type; };
void setHeight(int height) {mHeight = height; };
void setWidth(int width) {mWidth = width; };
void setBreadth(int breadth) {mBreadth = breadth; };
private:
//type of room
RoomType mType;
//floor dimensions - in feet
int mWidth;
int mBreadth;
//ceiling height - in feet
int mHeight;
};
#endif
ship.h
#ifndef ship_h
#define ship_h
#include "header.h"
const int MAX_BAY = 4;
const int MAX_LATRINE = 15;
const int MAX_BRIDGE = 1;
const int MAX_CABIN = 25;
const int MIN_BAY = 1;
const int MIN_LATRINE = 1;
const int MIN_BRIDGE = 1;
const int MIN_CABIN = 0;
const int MIN_ROOM_HEIGHT = 7;
const int MIN_ROOM_AREA = 20;
class Ship{
public:
Ship();
bool addRoom(const Room& theRoom);
string getDescription();
//Accessors
int getNumBays(){ return bayTotal; };
int getNumLatrines(){ return latrineTotal; };
int getNumBridges(){ return bridgeTotal; };
int getNumCabins(){ return cabinTotal; };
int getTotalSquareFootage(){ return totalSquareFootage; };
private:
Room Bay[MAX_BAY];
Room Latrine[MAX_LATRINE];
Room Bridge[MAX_BRIDGE];
Room Cabin[MAX_CABIN];
int bayTotal;
int latrineTotal;
int bridgeTotal;
int cabinTotal;
int totalSquareFootage;
bool isShipValid();
void addSquareFootage(float);
};
#endif
What kind of errors? Your issue might be including the same header more than once.
Try adding this to each header:
#ifndef ROOM_H
#define ROOM_H
... code ...
#endif
To be clear the 'ROOM_H' above needs to be unique to each header.
If you use #include "room.h" in different cpp files then you probably get a linker error because this below here is not a type declaration.
const string ROOM_STRINGS[NUM_ROOM_TYPES] = { "Bay",
"Latrine",
"Cabin",
"Bridge"
};
You are creating and allocating a variable with name ROOM_STRINGS. By declaring it in different cpp files you will have multiple copies of the same global variable which is an error. You could replace it with
static const string ROOM_STRINGS[NUM_ROOM_TYPES] = { "Bay",
"Latrine",
"Cabin",
"Bridge"
};
You will still have multiple copies but each cpp file will have its own private copy. A better solution is to move this declaration into the room cpp file together with the code of the getRoomName.
Or you could declare ROOM_STRINGS as extern in the header and then you still need to add the variable allocation in a cpp file.
I am working on implementing stack in C++ without STL libraries.
Here is my code for the Header file
// File: stack.h: header file
#ifndef STACK_H
#define STACK_H
class Stack {
int MaxStack;
int EmptyStack;
int top;
int* items;
public:
Stack(int); // Constructor
~Stack(); //Destructor
//Member Functions
void push(int);
char pop();
int empty();
int full();
};
#endif // STACK_H
And the Cpp file
// File: stack.cpp: stack functions
#include "stack.h"
using namespace std;
// Constructor with argument
Stack::Stack(int size) {
MaxStack = size;
EmptyStack = -1;
top = EmptyStack;
items = new int[MaxStack];
}
// Destructor
Stack::~Stack() { delete[] items; }
void Stack::push(int c) {
items[++top] = c;
}
char Stack::pop() {
return items[top--];
}
// Test for Full stack
int Stack::full() {
return top + 1 == MaxStack;
}
// Test for Empty stack
int Stack::empty() {
return top == EmptyStack;
}
Before making a main to test the class when I run this I get these two errors
!(http://postimg.org/image/pnjzd9axt/)
Any help on how to solve these two errors ?!
Thanks in advance
The error says that you don't have a main function.
The errors like:
Unresolved external symbol are the compiler way of saying: I want X function, I expect it to be declared but I can not find it in the compiled and linked modules
The main function is not defined.
Add the following to your source code: int main() { return 0; }
As indicated by Emil, the compiler cannot find the definition for the main function.
i have Point3D class in my project.
to create an object of Point3D i have added a cpp file & a header file as follows:
CreatePoint.h
#include "stdafx.h"
#pragma once
#include "Point3D.h"
//*******************************************************************
int counter = 0;
int size = 50;
Point3D **point;
//*******************************************************************
void create_array(int);//this will be called in main & pass 50//this is the method to create an array of pointers to Point3D
//*******************************************************************
void resize();//this increases the size of array if size - 5 elements are filled & increases size by 25
//*******************************************************************
Point3D *get_point(int);//this returns the pointer according to the index
//*******************************************************************
int get_index(Point3D *);//this returns the index of a point
//*******************************************************************
void move_point(int, int);//this interchanges the memory locations of 2 points
//*******************************************************************
void del_point(Point3D *);//this makes NULL value to the passed point
//*******************************************************************
void destruct_point();//this is called when the program ends by me
& the cpp file is:
#include "stdafx.h"
#include "CreatePoint.h"
//*******************************************************************
void create_array(int s)
{
point = new Point3D *[s];
for (int i = 0; i<s; i++)
{
point[i] = NULL;
}
}
//*******************************************************************
void resize()
{
Point3D **copy = new Point3D *[size];
for(int i = 0; i<size; i++)
{
copy[i] = point[i];
}
delete [] point;
size += 25;
create_array(size);
for(int i = 0; i<(size - 25); i++)
{
point[i] = copy[i];
}
delete [] copy;
}
//*******************************************************************
Point3D *get_point(int i)
{
if((size - counter) == 5)
resize();
return point[i];
}
//*******************************************************************
int get_index(Point3D *p)
{
for(int i = 0; i<size; i++)
{
if(point[i] == p)
return i;
}
return -1;
}
//*******************************************************************
void move_point(int a, int b)
{
Point3D *apt = get_point(a);
Point3D *bpt = get_point(b);
Point3D *t = new Point3D;
t = apt;
apt = bpt;
bpt = t;
delete t;
}
//*******************************************************************
void del_point(Point3D *p)
{
int d = get_index(p);
move_point(d, counter - 1);
point[counter - 1] = NULL;
}
//*******************************************************************
void destruct_point()
{
delete [] point;
point = NULL;
}
i am getting some linking errors:
stdafx.obj : error LNK2005: "class Point3D * * point" (?point##3PAPAVPoint3D##A) already defined in CreatePoint.obj
1>stdafx.obj : error LNK2005: "int counter" (?counter##3HA) already defined in CreatePoint.obj
1>stdafx.obj : error LNK2005: "int size" (?size##3HA) already defined in CreatePoint.obj
1>C:\Documents and Settings\SUMIT & AMIT\my documents\visual studio 2010\Projects\Maths\Debug\Maths.exe : fatal error LNK1169: one or more multiply defined symbols found
can anybody please help me!!!
also, any suggestions on the code will be appreciated :)
THANKS A LOT FOR READING MY POST
In header file use extern when declaring the variables, as:
//CreatePoint.h
extern int counter; //it is only a declaration
extern int size; //it is only a declaration
extern Point3D **point; //it is only a declaration
And in the source file, define and initialize them as:
//CreatePoint.cpp
#include "CreatePoint.h"
int counter = 0; //it is the definition
int size = 50; //it is the definition
Point3D **point; //it is the definition
You get multiple definitions error, because you include CreatePoint.h more than one .cpp file which defines the same variables more than once. Using extern in header file, avoids this, because it doesn't define them, it simply declares them, while the actual definition goes in the .cpp file.
The keyword extern tells the compiler to look for the definition elsewhere. The extern statements in the header are only declaration of the variables.
You are declaring & defining these variables directly in a header file. Every CPP file that includes this H file will get it's own definition of it, which is in violation of the One Definition Rule.
You need to change your design so that there is only one definition. You could make them extern in the H file:
CreatePoint.H
extern int counter;
extern int size;
extern Point3D **point;
...and then define them in the CPP file:
CreatePoint.CPP
int counter = 0;
int size = 50;
Point3D** point = 0;
Global variables are generally bad, however. You should redesign your code so as to not use them.
You need to declare variables as extern in the header because they are outside a function block. If they were declared inside a function, they would be considered automatic