Question: I need help figuring out why I keep getting a predefined and redefinition error in this code. I know it has to do with defining
I need help figuring out why I keep getting a predefined and redefinition error in this code. I know it has to do with defining the class in more than one place. I know I include the .h and .cpp of each file inside their corresponding namesake files. If I just include it into the main.cpp I have no problems but I would like to figure out how to fix the problem without resorting including everything in the main program. I am only getting the error with MyQueue.cpp and I'm not sure why. Can anyone figure it out?
Main CPP:
#include#include #include #include "MyStack.h" #include "MyQueue.h" using namespace std; bool isPalindrome(string sentence); int main(){ string sentence; char choice; do{ cout <<"Enter a sentence: "; getline(cin, sentence); cout << "\"" << sentence << "\""; if(isPalindrome(sentence)) cout << " is a palindrome" << endl; else cout << " is NOT a palindrome" << endl; cout << "Do you want to make another check? Y/N :"; cin >> choice; // get input char cin.ignore(); // ignore new lines }while(choice == 'y' || choice == 'Y'); cout << "Thanks for choose the "; return 0; } bool isPalindrome(string sentence){ // ignore whitespaces and non-alphabetic characters string s; for (int i = 0; i < sentence.length(); i++) { if (isalpha(sentence[i])) { s += tolower(sentence[i]); } } MyStack stack; MyQueue queue; for (int i = 0; i < s.length(); i++) { stack.push(s[i]); queue.push(s[i]); } // check if the sentence is a palindrome for (int i = 0; i < s.length(); i++) { if (stack.pop() != queue.pop()) { return false; } } return true; }
MyStack.h:
#ifndef MyStack_h #define MyStack_h #include#include using namespace std; template class MyStack{ public: MyStack(); void push(T item); T pop(); T peek() const; // const means that the function will not change the content of the object int size() const; bool isEmpty() const; private: vector v; // use a vector to hold data in stack }; #include "MyStack.cpp" #endif /* MyStack_hpp */
MyQueue.h:
#ifndef MyQueue_h #define MyQueue_h #include#include using namespace std; template
class MyQueue{ public: MyQueue(); T pop(); void push(T item); T peek() const; int size() const; bool isEmpty() const; private: list q; // we use a list to hold data for queue }; #include "MyQueue.cpp" #endif /* MyQueue_hpp */
MyQueue.cpp:
#include "MyQueue.h"
template
template
template
template
template
template
MyStack.cpp:
#include "MyStack.h"
template
template
template
template
template
template
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
