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.
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 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.
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).
I have a simple class which I cannot instantiate and I don't know why...
Please help me !
-------Test.cpp-------
#include<iostream>
using namespace std;
#include "meteo.h"
int main()
{
Meteo meteo;
}
-------meteo.h---------
#ifndef METEO_H
#define METEO_H
class Meteo
{
public:
Meteo();
int Get(int i);
private:
char *list[];
};
#endif
-------meteo.cpp--------
#include "meteo.h"
Meteo::Meteo()
{
list[]("Sec","Venteux","Humide");
}
int Meteo::Get(int i)
{
return list[i];
}
I get the error: "undefined reference to `Meteo::Meteo()'"
It seems that the problem is that the compiler issued an error when was compiling the constructor
Meteo::Meteo()
{
list[]("Sec","Venteux","Humide");
}
and did not generate the object module.
This record
list[]("Sec","Venteux","Humide");
is invalid.
Try to change the class definition like
class Meteo
{
public:
Meteo();
int Get(int i);
private:
const char *list[3];
};
and define the constructor like
Meteo::Meteo() : list { "Sec","Venteux","Humide" }
{
}
The other reason might be that you did not include object module meteo in the project.
Take into account that this member function
int Meteo::Get(int i)
{
return list[i];
}
is also wrong. The type of elements of the array is const char * not int.
I'm using a stack class, however every time I push something to the stack, the executable freezes and stops working once the line of code pushing is reached.
Could I please get some help on as to why?
My stack.h:
#ifndef STACK_H
#define STACK_H
#include <cassert>
namespace standard
{
class Stack
{
public:
static const int CAPACITY = 30;
void stack() {used=0;};
void push (const char entry);
void pop();
bool empty() const;
int size() const;
char top() const;
private:
char data[CAPACITY];
int used;
};
}
#endif
My stack.cpp:
#include "stack.h"
namespace standard
{
void Stack::push(const char entry)
{
assert(size() < CAPACITY);
data[used] = entry;
++used;
}
void Stack::pop()
{
assert(!empty());
--used;
}
char Stack::top() const
{
assert(!empty());
return data[used-1];
}
int Stack::size() const
{
return used;
}
bool Stack::empty() const
{
if (size() == 0)
return true;
else
return false;
}
}
My calc.cpp:
#include "stack.h"
#include <iostream>
#include <fstream>
using namespace std;
using namespace standard;
void main()
{
Stack myStack;
ifstream input;
input.open("tests.txt");
if (input.fail())
{
cerr << "Could not open input file." << endl;
exit(0);
}
char i;
input >> i;
cout << i;
myStack.push(i); // This is where things go wrong.
cin.get();
}
Thanks for any help!
It looks like you are not initializing used, you have something that may look like a constructor here but it is not:
void stack() {used=0;};
this is what it should look like:
Stack() { used=0;};
So without a constructor used is going to be some indeterminate value and will probably end up with you attempting to access data way out of bounds. Also main should always return int.
void stack() {used=0;};
should this be capitalised? & remove the void!
Stack myStack;
should this be
Stack myStack = new Stack();
if you don't initialise it, the variable myStack will be a "null pointer".
I think you wrote this function wrong:
void stack() {used=0;};
//^^extra ; here
should be
Stack() {used = 0;}
//^^Note that constructor has no return type
You have never really used the stack member function which return void. This results in the fact that used was never initialized. You probably mean the constructor of Stack. Meanwhile, you should use constructor initialization list:
Stack(): used(0) {}