So I am trying to call a function in my main.cpp file but I get "error: no matching function for call to 'Queue::Queue()."
Queue.h
#ifndef QUEUE_H
#define QUEUE_H
#include <iostream>
class Queue
{
public:
Queue(int);
~Queue();
//circular queue methods
void enqueue(std::string);
std::string dequeue(); //should send through network, call transmit msg
void printQueue();
bool queueIsFull(); //send when full
bool queueIsEmpty(); //send when empty
protected:
private:
int queueSize;
int queueHead;
int queueTail;
int queueCount;
std::string *arrayQueue;
};
#endif // QUEUE_H
Queue.cpp
#include "Queue.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
Queue::Queue(int qs)
{
queueSize = qs;
arrayQueue = new string[queueSize];
queueHead = 0;
queueTail = 0;
}
Queue::~Queue()
{
delete[] arrayQueue;
}
void Queue::enqueue(string word)
{
for (int i=0;i<10;i++)
{
arrayQueue[i] = word;
}
}
void Queue::printQueue()
{
for(int j=0;j<10;j++)
{
cout<<arrayQueue[j]<<endl;
}
}
main.cpp
#include <iostream>
#include "Queue.h"
using namespace std;
int main()
{
int userChoice;
Queue q;
while(2==2)
{
cout<<"======Main Menu======"<<endl;
cout<<"1. Enqueue word"<<endl;
cout<<"2. Dequeue word"<<endl;
cout<<"3. Print queue"<<endl;
cout<<"4. Enqueue sentence"<<endl;
cout<<"5. Quit"<<endl;
cin>>userChoice;
if (userChoice == 1)
{
string enqueueWord;
cout<<"word: ";
cin>>enqueueWord;
enqueue(enqueueWord);
}
if (userChoice == 2)
{
}
if (userChoice == 3)
{
}
if (userChoice == 4)
{
}
if (userChoice == 5)
{
}
}
return 0;
}
So to call the function from the header file I did "Queue q;" at the beginning of the int main() and then when I needed to call the function I did "q.enqueue(enqueueWord)." I also tried just doing "Queue::enqueue(enqueueWord), but that also didn't work and I get a different error. I feel like this is an easy fix but I just can't figure it out. Thanks for the help and feel free to ask me to clarify anything.
Queue q;
attempts to call the default constructor Queue::Queue. However, this constructor has been removed automatically since you explicitly declare a constructor, namely Queue::Queue(int), on your own.
Pass an appropriate argument to q when initialized, like
Queue q1(42); // pre-C++11 syntax
Queue q{42}; // available since C++11
(Note: 42 is only an exemplary value here.)
You could also use default arguments to keep the definition as-is and initialize the object with a default value.
Notes:
Why while(2==2)? while (true) is the common way.
Related
Ok just a heads up, this is my first question on here so i apologize if I don't include every relevant piece of info on my first go, but I'll do my best.
My problem is with a specific function I'm trying to write in main() that will print out data from nodes if their "category" matches the category that is searched for. I'm likely just fumbling with syntax as I'm still pretty new at this. To be clear, the exact problem is that all the function calls I've tried tell me *****"No instance of Overloaded function "BinTree::inOrderTraverse [with Type=CategorizedContact]" matches the argument list. argument types are: (void). Object type is BinTree***** Here's the relevant main() code:
#include <iostream>
#include <string>
#include <stdexcept> //invalid_argument
using namespace std;
#include "name.h"
#include "contact.h"
#include "address.h"
#include "BinTree.h"
#include "BinNode.h"
#include "CategorizedContact.h"
#include "Field.h"
#include "htmlfunc.h"
using namespace AddressInfo;
void printMenu();
void printByCat(CategorizedContact&, int);
int getMenuInput();
int validateMenuInput(Field input);
Field printCategoryMenu();
Field categorySelection();
int main()
{
Address tmpAddress;
Name tmpName, tmpName2;
CategorizedContact tmpContact, tmpContact2, itemToRemove;
BinTree<CategorizedContact> myBook;
Field tmpString1, categoryIn;
int menuOption = 0, node = 0, count = 0, categoryMenuOption = 0, categoryInt = 0;
CategorizedContact& tmp = tmpContact2; // I was just experimenting with trying to initialize
//a ref variable here, to make the function call work.
myBook.readFile("address.csv");
do
{
printMenu();
menuOption = getMenuInput();
switch (menuOption)
{
case 1:
cout << "\t***** Add Contact *****\n\n";
categoryIn = categorySelection(); //Prints Category menu and gets input
tmpContact.setCategory(categoryIn); //Assigns category choice to tmpContact
cin >> tmpContact; //Gets the rest of the contact info
myBook.addItem(tmpContact); //Adds contact to address book
myBook.writeFile("address.csv", '\n'); //Writes new contact to file
break;
case 2:
cout << "\n\t***** Count Contacts *****\n";
count = myBook.getNumUsed();
cout << "Number of Contacts: " << count;
cout << endl << endl;
break;
case 3:
cout << "\n\t***** Print Contacts By Category *****\n";
categoryIn = printCategoryMenu(); //Prints category menu and gets choice
if (categoryIn == "All Contacts")
myBook.printAll();
categoryInt = stoi(categoryIn); // converts to int to match required function parameters
myBook.inOrderTraverse(printByCat(tmp, categoryInt));
break;
That last line before the break; is the function call I'm struggling with.
Here's it's declaration:
void printByCat(CategorizedContact& tmp, int categoryInt)
{
int count = 1;
switch (categoryInt)
{
case 65:
if (tmp.getCategory() == "Business")
cout << count << ". " << tmp << endl;
break;
default:
cout << "Error" << endl;
break;
}
}
It's unfinished, and probably not even designed correctly but I can't tell until i manage to get the function call working.
Lastly here's the relevant code from my inOrderTraverse .h and .tem files pertaining to the problem.
#ifndef BINTREE_H
#define BINTREE_H
#include <cstdlib> // NULL
#include <string>
#include <iostream> // cout
#include <fstream>
#include <algorithm> // copy
#include "BinNode.h"
#include "CategorizedContact.h"
#include "Contact.h"
template <class Type>
class BinTree
{
public:
BinTree();
BinTree(const BinTree<Type>& source);
~BinTree();
BinTree<Type>& operator=(const BinTree<Type>& source);//assignment operator
int getNumUsed() const { return(used); }
void addItem(Type dataIn);
void printAll();
void writeFile(string fileName, char delimeter = '\n');
void readFile(string fileName);
void inOrderTraverse(void process(Type&, int));
void debugOn() { debug = true; }
void debugOff() { debug = false; }
private:
bool debug;
int used;
BinNode<Type>* root;
void inOrderTraverse(void process(Type&, int),
BinNode<Type>* cursor, int& count);
void write(BinNode<Type>* cursor, char delimeter,
ofstream& outFile);
void printInOrder(BinNode<Type>* cursor, int& count);
void free(BinNode<Type>* cursor);
void copyTree(BinNode<Type>* cursor);
BinNode<Type>* alloc(Type itemToAdd);
};
#include "BinTree.tem"
And just the relevant .tem portions...
template <class Type>
void BinTree<Type>::inOrderTraverse(void process(Type&, int))
{
int count = 1;
inOrderTraverse(process, root, count);
}
template <class Type>
void BinTree<Type>::inOrderTraverse(void process(Type&, int),
BinNode<Type>* cursor, int& count)
{
if (cursor != NULL)
{
// In order traverse
inOrderTraverse(process, cursor->left, count);
// PROCESS
process(cursor->data, count);
count++;
inOrderTraverse(process, cursor->right, count);
}
}
Before anyone suggests changing the InOrderTraverse(void process(Type&, int)), or the overloaded version, just Know that I'm required to implement it that way for my project.
the only freedom i have is with ***printByCat(CategorizedContact, int)****, that can be changed as long as it's still compatible with inOrderTraverse.
So as i hope u can now see, the function in main() printByCat() is meant to take in a category from the user, and then serve as an argument itself for inOrderTraverse(printByCat()). but I'm obviously making a fundamental mistake that i don't understand.
At this point any guidance would be appreciated, I'm not asking anyone to do the coding for me as i know you are against that, but I really just need to understand why the function call isn't working. I'm guessing the problem stems from my lack of experience with reference variables, but The error I'm getting seems to suggest the function printByCat() which is being taken as an argument of inOrderTraverse, does not meet the argument requirements because it's not a void function, but it is a void function.... so yea I'm a little lost. Anyways thanks for your time, and please let me know if i forgot anything.
Found out what it was, apparently I can't include the arguments of printbyCat() when using this function as an argument of inOrderTraverse(), so the function call should have simply been: myBook.inOrderTraverse(printByCat).
I still do not have much knowledge in C ++, I would like to ask for help for a task. I must create a stack, which is filled with data entered by the keyboard and the entire stack to write in external stack. I have made functions push, pop and simple program that displays the stack but before that data must be written in an external file. Can anybody help me with the external file?
#include <iostream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
struct elem
{ int key; elem *next;} *start=NULL, *p;
void push(int n)
{
p=start;
start=new elem;
start->key=n;
start->next=p;}
int pop(int &n){
if (start)
{
n=start->key;
p=start;
start=start->next;
delete p;
return 1;
}
else
return 0;
}
int main(){
int num;
cout<<"Input integers:"<<setw(10);
while (cin>>num)
{
push(num);
}
cout<<endl<<"Stack:"<<endl;
while(pop(num))
{
cout<<num<<endl;
}
return 0;
}
//you can use this pseudocode
ofstream outFile;
while(start!=-1){
outFile << pop() << endl;
This seems like a really easy fix, but I can't understand what it's coming from.
Any help fully appreciated!
The following 2 lines of code produce the following errors respectively.
vector <spades::player> players(4, player());
vector <spades::card> deck(52,card());
error: 'player' was not declared in this scope
error: 'card' was not declared in this scope
Below is my card.cpp
#include <iostream>
#include <sys/ioctl.h>
#include <cstdio>
#include <unistd.h>
#include <locale.h>
#include <ncursesw/ncurses.h>
#include "card.h"
namespace spades {
card::card()
{
cardSuit = 0;
cardNum = 0;
}
card::card(int suit, int number)
{
cardSuit = suit;
cardNum = number;
}
}
Below is my player.cpp
#include <iostream> // Stream declarations
#include <vector> //Vectors used to store deck and players hands
#include <string> //String declarations
#include <algorithm> //Shuffle Method
#include <sys/ioctl.h>
#include <cstdio>
#include <unistd.h>
#include <locale.h>
#include <ncursesw/ncurses.h>
#include "player.h"
namespace spades {
using namespace std;
player::player() {
score =0; //total score
bid = NULL; //bid for that round
tricksTaken = 0; //score for thast round
sandBag = 0; //the number of points you win, more than what you bid, every 10th bag = -100
doubleNil = false;
for(int i=0; i<13; i++)
hand.push_back(card());
}
void player::addCard(spades::card b){
for (int i=0; i<hand.size(); i++){
//compare card being played to the ones in your hand to search and determine which one to erase
if((hand.at(i).getCardNum() == 0) &&
(hand.at(i).getSuit() == 0))
{
hand.at(i).setCardNum(b.getCardNum());
hand.at(i).setSuit(b.getSuit());
return;
}
}
}
void player::removeCard(spades::card a) {
for (int i=0; i<hand.size(); i++){
//compare card being played to the ones in your hand to search and determine which one to erase
if((hand.at(i).getCardNum() == a.getCardNum()) &&
(hand.at(i).getSuit() == a.getSuit()))
{
hand.at(i).setCardNum(0);
hand.at(i).setSuit(0);
return;
}
}
}
}
The compiler is actually complaining about the arguments you pass to vector constructors. You specified player() and card() in the constructor arguments, while it is obvious that your types are actually named spades::player and spades::card. You correctly specified the spades:: part in template parameters. Why did you omit the spades:: part from the constructor arguments?
It should be
vector <spades::player> players(4, spades::player());
vector <spades::card> deck(52, spades::card());
It should be noted though that the explicit argument is unnecessary, so you can just do
vector <spades::player> players(4);
vector <spades::card> deck(52);
and get the same result.
Also you don't need the
namespace spades {
}
block in player.cpp, only around you class definition in the header file.
Maybe you ment
using namespace spades;
I have a struct defined in a header file with three other files that #include that header file. One is another header(queue.h) file that defines a very basic hash table and the other two are source codes where one is defining the functions from the hash table header(queue.cpp) and the other contains main(p2.cpp).
The problem that I'm having is that the struct seems to work fine in p2.cpp but in queue.h the compiler is telling me that the struct is undefined.
Here is p2.h containing the struct definition.
#ifndef __P2_H__
#define __P2_H__
#define xCoor 0
#define yCoor 1
#include <iostream>
#include <string>
#include "queue.h"
#include "dlist.h" //linked list which I know works and is not the problem
using namespace std;
struct spot {
float key[2];
string name, category;
};
#endif /* __P2_H__ */
I have queue.h included in this header so that I only have to include p2.h in p2.cpp.
Here is p2.cpp
#include <iostream>
#include <string>
#include <iomanip>
#include "p2.h"
using namespace std;
int main () {
cout << fixed;
cout << setprecision (4);
Queue hashTable;
spot *spot1 = new spot;
spot1->key[xCoor] = 42.2893;
spot1->key[yCoor] = -83.7391;
spot1->name = "NorthsideGrill";
spot1->category = "restaurant";
hashTable.insert(spot1);
Dlist<spot> test = hashTable.find(42.2893, -83.7391);
while (!test.isEmpty()) {
spot *temp = test.removeFront();
cout << temp->key[xCoor] << " " << temp->key[yCoor] << " " << temp->name << " " << temp->category << endl;
delete temp;
}
return 0;
}
Places and item in the hash table and takes it back out.
Here is queue.h
#ifndef __QUEUE_H__
#define __QUEUE_H__
#include <iostream>
#include <string>
#include "dlist.h"
#include "p2.h"
using namespace std;
class Queue {
// OVERVIEW: contains a dynamic array of spaces.
public:
// Operational methods
bool isEmpty();
// EFFECTS: returns true if list is empy, false otherwise
void insert(spot *o);
// MODIFIES this
// EFFECTS inserts o into the array
Dlist<spot> find(float X, float Y);
// Maintenance methods
Queue(); // ctor
~Queue(); // dtor
private:
// A private type
int numInserted;
int maxElts;
Dlist <spot>** queue;
// Utility methods
//Increases the size of the queue.
void makeLarger();
int hashFunc(float X, float Y, int modNum);
};
#endif /* __QUEUE_H__ */
Here is queue.cpp
#include <iostream>
#include <string>
#include <cstdlib>
#include "queue.h"
using namespace std;
bool Queue::isEmpty() {
return !numInserted;
}
void Queue::insert(spot *o) {
if (numInserted >= maxElts) {
makeLarger();
}
int index = hashFunc(o->key[xCoor], o->key[yCoor], maxElts);
queue[index] -> insertFront(o);
}
Queue::Queue() {
numInserted = 0;
maxElts = 1000;
queue = new Dlist<spot>*[maxElts];
for (int i = 0; i < maxElts; i++) {
queue[i] = new Dlist<spot>;
}
}
Queue::~Queue() {
for (int i = 0; i < maxElts; i++) {
delete queue[i];
}
delete[] queue;
}
void Queue::makeLarger() {
Dlist <spot>** temp = queue;
queue = new Dlist <spot>*[maxElts*2];
for (int i = 0; i < maxElts*2; i++) {
queue[i] = new Dlist<spot>;
}
for (int i = 0; i < maxElts; i++) {
while (!temp[i] -> isEmpty()) {
spot *spotTemp = temp[i] -> removeFront();
int index = hashFunc(spotTemp->key[xCoor], spotTemp->key[yCoor], maxElts*2);
queue[index] -> insertFront(spotTemp);
}
}
for (int i = 0; i < maxElts; i++) {
delete temp[i];
}
delete[] temp;
maxElts *= 2;
}
int Queue::hashFunc(float X, float Y, int modNum) {
return ((int)(10000*X) + (int)(10000*Y))%modNum;
}
Dlist<spot> Queue::find(float X, float Y) {
Dlist<spot> result;
Dlist<spot> *temp = new Dlist<spot>;
int index = hashFunc(X, Y, maxElts);
while (!queue[index] -> isEmpty()) {
spot *curSpot = queue[index] -> removeFront();
if ((curSpot->key[xCoor] == X) && (curSpot->key[yCoor] == Y)) {
result.insertFront(new spot(*curSpot));
}
temp -> insertFront(curSpot);
}
delete queue[index];
queue[index] = temp;
return result;
}
I believe that the problem is in my queue.h file because it's where I get all of the errors like "spot has not been declared". Every time spot appears in queue.h I have at least one error. I searched around for anything like this but all I could find was people trying to share one instance of a struct across multiple source files, or the obvious question of putting a struct in a header and including that header across multiple source files(which is what I'm doing but my problem seems to be a rather unique one).
You are including queue.h within the header that actually defines spot, so by the point the file is actually included spot has not been defined yet.
For your scope guards, note that identifiers starting with a double underscore are reserved by the implementation, don't use them.
And this is a poor choice even in plain C:
#define xCoor 0
#define yCoor 1
use this instead:
enum {
xCoor = 0
, yCoor = 1
};
Ok first never ever using "using" clauses in header files (it destroys the purposes of namespaces)
2nd provide a complete example that fails to compile
In addition to what others have said, you also have a circular reference error, which can also lead to similar undefined symbol errors. You have queue.h include p2.h, which includes queue.h.
Hey guys, just learning about composition of classes and ran into this error.
Gradebook.h
#ifndef GRADEBOOK_h
#define GRADEBOOK_h
#include "StudentRec.h"
#include <iostream>
#include <string>
class GradeBook
{
public:
GradeBook();
GradeBook(string initLastName, int studGrades);
void AddStudent(string initLastName, int studGrades);
void ShowStudents();
void UserInterface();
private:
static const int numStudents=20;
StudentRec student[numStudents];
static int studentCounter;
static int gradeCounter;
};
#endif
Gradebook.cpp
#include "Gradebook.h"
#include "StudentRec.h"
#include <iostream>
#include <string>
using namespace std;
GradeBook::GradeBook()
{}
GradeBook::GradeBook(string initLastName, int studGrades)
{}
void GradeBook::AddStudent(string initLastName, int studGrades)
{
gradeCounter++; //Increments variable responsible for tracking # of grades per student
StudentRec newStudent(initLastName, studGrades); //creates new student object
student[studentCounter]=newStudent; //Assigns new student object to array
studentCounter++; //Increments variable responsible for tracking # of students
}
void GradeBook::ShowStudents()
{
for(int i=0;i<studentCounter; i++){ //Displays information for each student instance
cout<<student[i].GetLastName()<<' ';
for(int j=0; j<gradeCounter; j++)
cout<<student[i].GetGrades(j)<<' ';
cout<<endl;
}
}
void GradeBook::UserInterface()
{
char choice=' ';
string studLastName;
int studGrade;
cout<<"Welcome to GradeBook, this program stores students"
<<" grades by last name. To ADD a student press the 'A'"
<<" key. To LIST all students, press the 'L' key. To "
<<" QUIT, press the 'Q' key."<<endl<<endl;
cin>>choice;
choice=toupper(choice);
while(choice!='Q')
{
if(choice='A'){
cout<<"To add a student, please enter their last name"
<<" followed by a space and a non-negative grade"
<<" Ex. McClure 96";
cin>>studLastName>>studGrade;
AddStudent(studLastName, studGrade);
}
else if(choice='L'){
cout<<"This is a list of all students in GradeBook"
<<endl<<endl;
ShowStudents(); //Displays all StudentRec objects
}
else if(choice!='Q')
cout<<"Please enter another letter"<<endl;
cout<<"To ADD a student press the 'A' key. To LIST all students, press the 'L' key. To "
<<" QUIT, press the 'Q' key."<<endl<<endl;
}
}
Main.cpp
#include <iostream>
#include <string>
#include "StudentRec.h"
#include "Gradebook.h"
using namespace std;
int main()
{
GradeBook gradeBook;
UserInterface();
return 0;
}
StudentRec.cpp
#include <iostream>
#include <string>
#include "StudentRec.h"
using namespace std;
StudentRec::StudentRec()
{
lastName=" ";
for(int i=0;i<numGrades; i++)
grades[i]=0;
}
StudentRec::StudentRec(string initLastName, int studGrade)
{
static int gradeCounter=0;
lastName=initLastName;
grades[gradeCounter]=studGrade;
}
string StudentRec::GetLastName()
{
return lastName;
}
int StudentRec::GetGrades(int gradeNum)
{
return grades[gradeNum];
}
void StudentRec::AddGrades(int studGrade)
{
gradeCounter++;
if(gradeCounter<=numGrades)
grades[gradeCounter]=studGrade;
else
cout<<"Too many grades for this student";
}
StudentRec.h
#ifndef STUDENTREC_h
#define STUDENTREC_h
#include <iostream>
#include <string>
using namespace std;
class StudentRec
{
public:
StudentRec();
StudentRec(string initLastName, int studGrade);
string GetLastName();
int GetGrades(int gradeNum);
void AddGrades(int studGrade);
private:
static const int numGrades=10;
static int gradeCounter;
string lastName;
int grades[numGrades];
};
#endif
In the Main.cpp file, I get an error I can't find the solution for. It reads
error: "UserInterface" was not declared in this scope. I got this error while compiling in XCode
I got error C3861: 'UserInterface': identifier not found
Obviously i've tried it in two IDEs, I also have the StudentRec.cpp and .h, but not sure you need them. Thanks in advance for the help
It appears that UserInterface() is actually a member function of GradeBook, correct?
If so, you need to add a declaration for the member function in the GradeBook class declaration:
class GradeBook
{
public:
GradeBook();
GradeBook(string initLastName, int studGrades);
void AddStudent(string initLastName, int studGrades);
void ShowStudents();
void UserInterface(); // Added
// ...
private:
// ...
};
This way, the compiler will "know" that the UserInterface() function exists as a member function. You then provided the definition in void GradeBook::UserInterface() in your .cpp file.
Then you need to call it on a GradeBook instance, like the gradeBook variable in your main() function:
int main()
{
GradeBook gradeBook;
// This calls the member function UserInterface() on the gradeBook variable.
gradeBook.UserInterface();
// This calls the global UserInterface(), which doesn't exist.
// UserInterface();
return 0;
}
UserInterface() is a method of GradeBook. The call probably needs to be:
gradeBook.UserInterface();