C++ error LNK2019 && fatal error LNK1120: 1 unresolved externals - c++

I am trying to work on a homework assignment for school and am going above what the teacher is asking for the assignment -> I have created a "list" class. I keep running into these two errors after adding the 'add()' method to the program - along with the 'newIncomeTax()' methods
error LNK2019: unresolved external symbol "public: void __thiscall List::add(class IncomeTax *)" (?add#List##QAEXPAVIncomeTax###Z) referenced in function _main driver.obj
and
fatal error LNK1120: 1 unresolved externals
I hope this will be enough code for anyone trying to help me:
note: the functions below are not in the order that they appear in the original code
(if that may be the problem I can provide all the code that i'm using)
list.h
#ifndef LIST_H
#define LIST_H
#include "IncomeTax.h"
class List
{
private:
IncomeTax * First;
IncomeTax * Last;
int num_in_list;
public:
List () { num_in_list = 0; First = NULL; Last = NULL; }
int get_num_in_list() { return num_in_list; }
IncomeTax * getFirst() { return First; }
IncomeTax * getLast() { return Last; }
void del_frnt ();
void push_front (IncomeTax *);
void push_back (IncomeTax *);
void del_last ();
void add (IncomeTax*);
IncomeTax * pop_back ();
IncomeTax * pop_front ();
IncomeTax * get (int);
};
#endif
note: from what I've seen the list that **I've** made behaves similarly to the default
the 'add' method from list.cpp
void List:: add (IncomeTax * IncomeTax_to_be_added) {
if (num_in_list == 0) { First = IncomeTax_to_be_added; Last = IncomeTax_to_be_added; }
else if (num_in_list != 0 ) {
Last->setNext(IncomeTax_to_be_added);
IncomeTax_to_be_added->setPrevous(Last);
Last = IncomeTax_to_be_added;
}
num_in_list++;
}
IncomeTax.h
#ifndef INCOME_TAX
#define INCOME_TAX
#include <iostream>
#include <string>
#include "conio.h"
#include <cassert>
using namespace std;
class IncomeTax {
private:
double incm;
double ajIncm;
double subtract;
double taxRate;
double add;
bool married;
void calcIncome_m ();
void calcIncome_s ();
public:
IncomeTax () { incm = 0; subtract = 0; taxRate = 0; add = 0; add = false; }
// married -> is by default false
void setmarried ( bool stats ) { married = stats; }
void setIncm (double in ) { incm = in; }
void setSubtract ( double sub ) { subtract = sub; }
void setTaxRate ( double rate ) { taxRate = rate; }
void setAdd ( double Add ) { add = Add; }
void setAjIncome ( double AJincome ) { ajIncm = AJincome; }
bool getmarried () { return married; }
double getIncm () { return incm; }
double getsubtract () { return subtract; }
double getTaxRate () { return taxRate; }
double getAdd () { return add; }
double getAJincome () { return ajIncm; }
void calcIncome ();
void pintIncome ();
};
#endif
IncomeTax.cpp
#include "IncomeTax.h"
using namespace std;
void IncomeTax::calcIncome(){
assert (incm != 0);
if (married) { calcIncome_m(); }
if (!married) { calcIncome_s(); }
ajIncm = (incm - subtract);
ajIncm -= (ajIncm * taxRate);
ajIncm += add;
}
void IncomeTax::calcIncome_m() {
assert (incm != 0);
... huge nested if statements ...
they set subtract, add, taxRate...
}
void IncomeTax::calcIncome_s() {
assert (incm != 0);
... huge nested if statements ...
they set subtract, add, taxRate...
}
void IncomeTax::pintIncome () {
assert (incm != 0);
assert (ajIncm != 0);
std::cout.precision(2);
cout << "\tTaxable Income: " << incm << endl;
cout << "\tAjusted Income: " << ajIncm << endl;
cout << "\tTax: " << (incm - ajIncm) << "\n" << endl;
}
Driver.cpp
#include <conio.h>
#include <iostream>
#include <string>
#include <cassert>
#include "IncomeTax.h"
#include "List.h"
using namespace std;
void getMaritalStatus( IncomeTax new_tax) {
bool done = false;
char stt = ' ';
while ( !done ) {
cout << "\nPlease declare weather you are filing taxes jointly or single" << "\n";
cout << "\t's' = single\n\t'm' = married" << endl;
stt = getch();
if ( stt == 's' || stt == 'm' ) { done = true; }
if ( stt == 's' ) { new_tax.setmarried(true); }
if ( ! (stt == 's' || stt == 'm') ) { cout << "\nyou have entered an invald symbol... \n" << endl; }
if(cin.fail()) { cin.clear(); }
}
}
void get_Income ( IncomeTax new_tax) {
double _incm = 0;
char status = ' ';
bool done = true;
while ( done ) {
cout << "Please enter your TAXABLE INCOME:" << endl;
cin >> _incm;
if ( _incm > 0 ) { new_tax.setIncm(_incm); done = false; }
if ( _incm <= 0 ) { cout << "\nthe number you entered was less than zero\nplease enter a valad number...\n" << endl; }
if(cin.fail()) { cin.clear(); }
}
}
IncomeTax newIncomeTax () {
IncomeTax new_tax;
IncomeTax * temp;
get_Income(new_tax);
getMaritalStatus(new_tax);
new_tax.calcIncome();
return new_tax;
}
bool again () {
bool done = false, answer = false;
char yn = ' ';
while ( !done ) {
cout << "\nWould you like to calculate another Income tax? (y/n)" << endl;
yn = getch();
if ( yn == 'y' || yn == 'n' ) { done = true; }
if ( yn == 'y' ) { return false; }
if ( yn == 'n' ) { return true; }
if ( ! (yn == 's' || yn == 'n') ) { cout << "\nyou have entered an invald symbol... \n" << endl; }
if(cin.fail()) { cin.clear(); }
}
}
int main () {
IncomeTax new_tax;
List L;
bool done = false;
while (!done) {
IncomeTax temp = newIncomeTax();
IncomeTax * ptr = &temp;
L.add(ptr);
done = again();
};
return 0;
};
I know that there are many better ways to do the 'if' statements -> i just decided that it would be efficient to just use the if statments -> the professor has stated that there is no need to go beyond this.
Since this is homework I would love to get some feed back on ways that I can use better programing techniques. thanks!
I'm using VS express 2008 C++

Since this is homework I would love to get some feed back on ways that I can use better programing techniques. thanks!
Create separate headers/implementation files for your classes. Don't put all of them in a single header. And put your main in a separate implementation file (call it main.cpp, if you will).
Cut out all the functions that you are not using, and try to create the minimal example that reproduces your error -- that'll help you figure out your issues easily and without needing to come back to SO every now and then. Add one function at a time and see if it compiles, then move on to the next, rinse and repeat.
Another good idea when adding functions is to use stubs -- empty functions just to check if you don't hit any of these unresolved symbol errors (when you're starting out).
You will also need to learn about the syntax -- you don't need a semi-colon after the ending brace of while. You will also learn that members are initialized in the order in which they are declared (so your int member should ideally follow your IncomeTax members). You will need to know what initializer-lists are. And you will need to know about forward declaring.
In short, you will need a book and lots of practice. Here's your code refactored a bit using some of the things I explained above:
class IncomeTax {};
class List
{
private:
IncomeTax * First;
IncomeTax * Last;
int num_in_list;
public:
List () :
First(NULL),
Last(NULL),
num_in_list (0)
{}
~List()
{
// free First and Last ?
}
void add (IncomeTax*) {}
};
int main () {
IncomeTax new_tax;
List L;
bool done = false;
while (!done) {
IncomeTax temp;
L.add(&temp);
done = true;
}
return 0;
}

There's something else you're not telling us here since this should link flawlessly (it did here). I just moved the List class declaration before main() to avoid the class is declared when compiling main but otherwise everything compiles fine.
// Something declared in this order (in the same file or through .h files) should compile & link correctly
class IncomeTax { ... };
class List { ... };
int main() { ... };

It looks like you may have forgotten to add the IncomeTax object file (IncomeTax.o, IncomeTax.obj, etc) into your link command line, and the linker is telling you that it can't find the method definition.
You can test this by temporarily creating a single "whole_project.cpp" file that contains all the code copy-pasted sequentially. If it compiles and links correctly that way, then you just need to edit your makefile/IDE project file/manual command line to specify that it also needs to include the object file.
It only shows the one error because you're only actually calling the add function and none of the other non-inline functions within the list class.
Finally, double check the logic you're using to add items to the list. I believe the temporary you're adding will cause problems since the object goes away as soon as the while loop enters its next iteration.

Related

while loop in class won't execute c++

I have a while loop as part of a class.
#include <iostream>
#include <iomanip>
#include <fstream>
struct familyFinance{ //add 3rd member familyFinance;
int acctNos; float Balance; struct familyFinance *nextNodePointer;
struct familyFinance *dynMemory;
};
using namespace std;
class myFinanceClass {
private:
string fileName="";
familyFinance *ptrHead = nullptr;
public:
void setFileName(string){ fileName="Lab5Data.txt";}
void readFileAndBuildLinkedList(){
ifstream Lab3DataFileHandle;
familyFinance *ptrHead=nullptr;
//familyFinance *dynFinancePtr=nullptr;
familyFinance *tempPtr;
tempPtr=ptrHead;
Lab3DataFileHandle.open(fileName.c_str());
while (!Lab3DataFileHandle.eof( )) {
familyFinance *dynFinancePtr= new familyFinance;
Lab3DataFileHandle >> dynFinancePtr -> acctNos;
Lab3DataFileHandle >> dynFinancePtr -> Balance;
// familyFinance *nextNodePointer = nullptr;
if (ptrHead == nullptr) {
ptrHead = dynFinancePtr;
}
else {
tempPtr = ptrHead;
while (tempPtr -> nextNodePointer != nullptr )
tempPtr = tempPtr->nextNodePointer;
tempPtr->nextNodePointer = dynFinancePtr;
}
}
Lab3DataFileHandle.close();
}
void spitThemOut(){
familyFinance *tempNodePtr;
tempNodePtr = ptrHead;
Here is the While Loop
while (tempNodePtr) {
cout << "Acct, Balance: " << setw(3)
<<ptrHead->acctNos << " " <<ptrHead->Balance << endl;
tempNodePtr = tempNodePtr->nextNodePointer;
}
}
When I call the function from class in main I know it can read the function it just won't execute the while loop. What do I need to change to execute the while loop. It would be much apprenticed if you showed an example in your answer. Thank you for your time.
If the while loop is in the method and defined in that class, that won't execute, cause it's not allowed by the language. Methods defined within the class are not allowed to have any loops. There are a few more restrictions that apply for methods defined within the class. Such a case can be solved by declaring the method in the class but defining it outside the class as shown below
class myFinanceClass {
... // all the code before spitThemOut()
void spitThemOut();
};
void myFinanceClass::spitThemOut() {
... // code to work
while (tempNodePtr) {
...
}
}

Trouble with how to declare (or define) a function in a header

I'm struggling with implementation of a function that I define in my header file of my c++ program. I think I am misunderstanding how it works, but most reading on the web doesn't spell it out clear enough for my peon brain to understand.
I'm trying to make a 'sort_name' function that sorts an array of private classes based on the c-string "name" when the function is invoked.
Unfortunately I keep running into errors when trying to use it.
Here's my courses_main.cpp's main function:
int main()
{
Course* courses[10] = {};
int selection;
int size = 0;
do
{
selection = menu();
if (selection == 1)
{
if (size < 10)
add(courses, size);
else
std::cout << "\nUnable to add more classes.";
}
else if (selection == 2)
{
edit(courses, size);
}
else if (selection == 3)
{
}
else if (selection == 4)
{
sort_name(courses, size);
for (int i = 0; i < size; i++)
{
courses[i]->display();
}
}
else if (selection == 5)
{
}
else if (selection == 6)
{
}
else if (selection == 7)
{
break;
}
else
{
std::cout << "\nInvalid selection.";
}
} while (selection != 7);
std::cout << "\nPress any key to exit.";
(void)_getch();
return 0;
}
Here is my courses_functions.cpp where I define the sort_name function:
void swap_ptrs(Course*& pt1, Course*& pt2) //Passes the pointers by reference
{
Course* tmp = pt1;
pt1 = pt2;
pt2 = tmp;
}
void Course::sort_name(Course* co_ptr[], int size) //has to be apart of the class (Course::) to have access to the name data
{
bool swap;
do
{
swap = false;
for (int i = 0; i < size - 1; i++)
{
if (strcmp(co_ptr[i]->name, co_ptr[i + 1]->name) > 0) //We're now comparing and swapping pointers
{
swap_ptrs(co_ptr[i], co_ptr[i + 1]);
swap = true;
}
}
} while (swap);
}
And here is my courses.h header where I define(?) the function:
#ifndef COURSE_H
#define COURSE_H
#include <iostream>
#include <conio.h>
#include <iomanip>
#include <stdio.h>
#include <string.h>
#include <ctime>
#include <fstream>
#include <cstdlib>
class Course
{
private:
char name[10] = "", grade;
int units;
public:
Course()
{
name;
grade;
units = 0;
}
void read() //Initializes course and collects information from user
{
std::cout << "\nEnter course name: ";
std::cin.getline(name, 10, '\n');
std::cout << "\nEnter number of units: ";
std::cin >> units;
std::cout << "\nEnter grade received: ";
std::cin >> grade;
std::cin.ignore();
}
void display() const //Displays course to user
{
std::cout << name << ' ' << units << ' ' << grade << std::endl;
}
~Course() //Destructor frees allocated dynamic memory
{
std::cout << "\nDeleting any dynamically created object";
}
void sort_name(Course* co_ptr[], int size);
};
#endif // COURSE_H
I'm not understanding much about classes outside of how they're extremely similar to structs, so any direction would be welcome thanks!
A better code organization would be to declare the functions in the .h file and implement them in the.cpp.
Here is a working sample without .cpp for simplification. Only Courses.h and main.
With .cpp your program should be somethong like this:
Course.h
#ifndef COURSE_H
#define COURSE_H
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std; //<-- for test pusposes, you should use std:: scope
class Course
{
private:
string name;
int units, grade;
public:
Course(); //<-- the code you have inside the constructor, only units = 0,
// does somenthing, you should initialize all the members.
Course(string name);
void read();
void display() const;
~Course(); //<-- to dealocate dynamic memory you need to really dealocate it with delete.
string getName() const;
};
#endif // COURSE_H
And in your .ccp the implementation:
Course.cpp
#include "Course.h"
Course::Course(){ /*do stuff*/ }
Course::Course(string name) : name(name) { /*do stuff*/ } //<-- initializing name here
void Course::read() {/*do stuff*/ }
void Course::display() const {/*do stuff*/ }
Course::~Course() {/*do stuff*/ }
string Course::getName() const { return name; }
For sorting you don't need anything fancy you have sorting tools and data structures in the C++ libraries that make your job easy, like vector for objects container and sort for sorting.
Main
#include "Course.h"
bool sorting(Course course1, Course course2) { //conditional function for sort (#include <algorithm>)
return course1.getName() < course2.getName();
}
int main() {
vector<Course> courses = { Course("zed"), Course("albert")}; // adding courses
courses.push_back(Course("mary")); // adding some more
courses.push_back(Course("john"));
courses.push_back(Course("ana"));
courses.push_back(Course("charles"));
sort(courses.begin(), courses.end(), sorting); //<-- sorting
for (Course c : courses) {
cout << c.getName() << " ";
}
}
Output:
albert ana charles john mary zed

I can't seem to get the msvc linker to work properly on vscode

I have this really simple program that's made up of 2 files.
main.cpp has the main function:
[main.cpp]
#include <iostream>
#include <string>
#include "calculator.h"
using namespace std;
int main() {
Calculator calc;
do {
string op, left, right;
float out;
cout << endl << "insert an operator and two numbers: ";
cin >> op;
if (calc.isOperator(op)) {
cin >> left;
cin >> right;
out = calc.doOp(op, left, right);
cout << endl << "result: " << endl;
}
else
cout << endl << "invalid operator" << endl;
} while(true);
}
calculator.cpp has the Calculator class and calculator.h has a declaration for the class and every function or variable in it.
[calculator.cpp]
#include <iostream>
#include <cmath>
#include <vector>
#include <string>
using namespace std;
class Calculator {
vector<float>* mem_stack;
public:
Calculator() {
mem_stack = new vector<float>();
}
~Calculator() {
delete mem_stack;
}
float memPeek() {
return (*mem_stack).back();
}
float memPeek(const int& age) {
return (*mem_stack)[(*mem_stack).size() - age];
}
float doOp(const string& op, string& left, string& right) {
float a, b;
if (left[0] == 'r') {
left = left.substr(1, left.size() - 1);
a = memPeek(stoi(left));
}
else
a = stoi(left);
if (right[0] == 'r') {
right = right.substr(1, right.size() - 1);
b = memPeek(stoi(right));
}
else
b = stoi(right);
float out;
if (op == "+")
out = a + b;
else if (op == "-")
out = a - b;
else if (op == "*")
out = a * b;
else if (op == "/")
out = a / b;
(*mem_stack).push_back(out);
return memPeek();
}
bool isOperator(const string& op) {
bool out;
out = op == "+" && op == "-" && op == "*" && op == "/";
return out;
}
};
[calculator.h]
#pragma once
#include <vector>
#include <string>
class Calculator {
private:
std::vector<float>* mem_stack;
public:
Calculator();
~Calculator();
float memPeek();
float memPeek(const int& age);
float doOp(const std::string& op, std::string& left, std::string& right);
bool isOperator(const std::string& op);
};
When I try to compile the program I get unresolved linking errors in the main function. They all look like this:
main.obj : error LNK2019: unresolved external symbol
I get them for every function from calculator.cpp called in main, including the constructor and destructor
I have looked up everything I could find on this but I still get those errors. Could anybody help me?
I'm still just a rookie.
Welcome to StackOverflow!
You may have solved this in the meantime, but your problem is pretty simple: in your Calculator.cpp file, you're basically redeclaring another Calculator class, which shadows the original one, that ends up with no functions defined for it (just the declarations in the .h file). To solve this, you instead declare your member functions with ClassName::functionName() in the .cpp instead.
Didn't try compiling, but this should work:
[calculator.cpp]
#include <iostream>
#include <cmath>
#include <vector>
#include <string>
using namespace std;
Calculator::Calculator() {
mem_stack = new vector<float>();
}
Calculator::~Calculator() {
delete mem_stack;
}
float Calculator::memPeek() {
return (*mem_stack).back();
}
float Calculator::memPeek(const int& age) {
return (*mem_stack)[(*mem_stack).size() - age];
}
float Calculator::doOp(const string& op, string& left, string& right) {
float a, b;
if (left[0] == 'r') {
left = left.substr(1, left.size() - 1);
a = memPeek(stoi(left));
}
else
a = stoi(left);
if (right[0] == 'r') {
right = right.substr(1, right.size() - 1);
b = memPeek(stoi(right));
}
else
b = stoi(right);
float out;
if (op == "+")
out = a + b;
else if (op == "-")
out = a - b;
else if (op == "*")
out = a * b;
else if (op == "/")
out = a / b;
(*mem_stack).push_back(out);
return memPeek();
}
bool Calculator::isOperator(const string& op) {
bool out;
out = op == "+" && op == "-" && op == "*" && op == "/";
return out;
}
As a side note, I don't know of your programming background, but one thing struck me out as very odd in your code. Maybe you've come from Java or C#, where you always have to initialize object member variables; C++ is a bit more like C in this respect, in that it allows you to hold objects by value, and not only reference. Which means you don't have to have a pointer to your vector<float>, nor allocate/deallocate it yourself; let the compiler do the work for you and use it by value.
So, instead of doing std::vector<float>* mem_stack;, simply do std::vector<float> mem_stack;; this makes operations like (*mem_stack).push_back(out); (or the alternative mem_stack->push_back(out);, using the -> deference operator) much cleaner: mem_stack.push_back(out);

Changing a value of an element in an object that is stored in a vector in another object through an external function in C++

So made a class called ‘Item’, and the object of that class will have a 100% condition at the start, the Player stores items (with name “apple” in this case) whenever I tell him to. In the degradeT function I want to pass the whole vector containing the items that the player has picked up by far and then change the condition of each Item in that vector by -1 through the chCond function.
first error:
initial value of reference to non-const must be an lvalue
second error:
'void degradeT(std::vector<Item,std::allocator<_Ty>> &)': cannot convert argument 1 from 'std::vector<Item,std::allocator<_Ty>>' to 'std::vector<Item,std::allocator<_Ty>> &'
#include "pch.h"
#include <iostream>
#include <string>
#include <vector>
using std::cout; using std::cin; using std::endl;
using std::string; using std::vector; using std::to_string;
class Item {
private:
string name; // Item name
float condition; // Item condition
bool consumable; // Is the item consumable
public:
Item() {}
Item(string a, float b, bool c) { name = a; condition = b; consumable = c; }
Item(string a, bool c) { name = a; condition = 100.f; consumable = c; }
string getName() {
return name;
}
float getCond() {
return condition;
}
bool isCons() {
return consumable;
}
void chCond(float a) { // Change Item condition
condition += a;
}
};
//-----------------------
class Player {
private:
vector<Item> plItems; // Item container
public:
Player() {}
void pickUpItem(Item a) { // Adding Items to inventory
plItems.push_back(a);
cout << a.getName() << " added to inventory!\n";
}
void checkItemConds() { // Checking condition of all items
for (unsigned int a = 0, siz = plItems.size(); a < siz; a++) {
cout << plItems[a].getName() << "'s condition is: " << plItems[a].getCond() << "%\n";
}
}
Item returnItem(unsigned int a) { // Return a specific Item
return plItems[a];
}
int getCurInvOcc() { // Get cuurent inventory occupation
return plItems.size();
}
vector<Item> getPlItems() { // Return the vector (Item container)
return plItems;
}
};
//-------------------------
void degradeT(vector<Item>& Itemss); // Degrade item after some time
//-------------------------
int main()
{
Player me; // me
string inp; // input
int num = 1; // apple 1, apple 2, apple 3...
while (inp != "exit") {
cin >> inp;
if (inp == "addApple") {
Item apple(("apple " + to_string(num)), true);
me.pickUpItem(apple);
num++;
}
if (inp == "checkItemConds") {
me.checkItemConds();
}
if (inp == "timeTick") {
// This doesn't have anything to do with time I just want to test the function manually
degradeT(me.getPlItems());
}
}
system("PAUSE");
return 0;
}
void degradeT(vector<Item> &Itemss) {
for (unsigned int a = 0, siz = Itemss.size(); a < siz; a++) {
Itemss[a].chCond(-1);
cout << Itemss[a].getName() << endl;
}
}
I'm not sure what your question is, but your error is related to the function void degradeT(vector<Item> & Itemss).
This functions expects a reference but you are passing an r-value. You can either return a reference with getPlItems() or pass an l-value to degradeT.

Class Errors with Pointers

I'm currently writing a class for a program and this is what I'm attempting to accomplish...
Setup: Sets m_ptrEmployee to NULL and m_beginHour to hour.
AssignEmployee: Sets m_ptrEmployee to employee.
GetEmployeeName: Uses m_ptrEmployee and Employee.GetName to return the employees
name. Returns “UNALLOCATED”, if m_ptrEmployee is NULL.
Output: Uses m_ptrEmployee and Employee.GetName to display m_beginHour and the
employee’s name something like this, “8:00 - David Johnson” or like this, “8:00 -
UNALLOCATED”, if m_ptrEmployee is NULL.
Reset: Resets m_ptrEmployee to NULL.
GetIsSet: Returns true, if m_ptrEmployee is not NULL and false otherwise.
Here is my code...
#include <string>
using namespace std;
#include "Employee.h"
class Schedule
{
public:
void Setup( int hour )
{
m_ptrEmployee = NULL;
m_beginHour = hour;
};
void AssignEmployee( Employee* employee )
{
m_ptrEmployee = employee;
};
string GetEmployeeName()
{
if (m_ptrEmployee = NULL)
return "UNALLOCATED"
else
return Employee.GetName()
};
void Output()
{
if (m_ptrEmployee = NULL)
cout>> m_beginHour>>"--">>"UNALLOCATED">>endl;
else
cout>>m_beginHour>>"--">>GetName()>>endl;
}
void Reset()
{
m_ptrEmployee = NULL;
}
bool GetIsSet()
{
if (m_ptrEmployee != NULL)
return true;
else
return false;
}
private:
Employee* m_ptrEmployee;
int m_beginHour;
};
GetName() is included in a previous class and it is...
public:
void Setup( const string& first, const string& last, float pay );
{
m_firstName = first;
m_lastName = last;
m_payPerHour = pay;
m_activeEmployee = true;
}
string GetName()
{
return m_firstName+""+m_lastName
};
I'm receiving multiple errors and I'm not sure what I'm doing wrong? This is my first time attempting to write classes with pointers, so I apologize if my code is absolutely awful.
Here are some corrections:
In general, be careful with comparisons in C++. You can't use the intuitive = when comparing two things. You have to use ==. If you use =, it results in an assignment and not a test. Also, do not forget your semicolon ; at the end of a statement.
Bad comparison:
if (m_ptrEmployee = NULL) //Assigns NULL to m_ptrEmployee and then tests m_ptrEmployee
//Always false because m_ptrEmployee was just assigned NULL
Good comparison:
if (m_ptrEmployee == NULL) //Better. This is false only when m_ptrEmployee equals NULL
When you want to access a member of a class through a pointer (such as m_ptrEmployee), you have to use the -> operator like so: m_ptrEmployee->GetName()
Operator cout is used with the << operator, and not the >> operator.
I have annotated the places in your code where you made mistakes.
#include <string>
using namespace std;
#include "Employee.h"
class Schedule
{
public:
void Setup( int hour )
{
m_ptrEmployee = NULL;
m_beginHour = hour;
};
void AssignEmployee( Employee* employee )
{
m_ptrEmployee = employee;
};
string GetEmployeeName()
{
if (m_ptrEmployee == NULL) //Comparison always takes double ==
return "UNALLOCATED";
else
return m_ptrEmployee->GetName(); //Use employee pointer with -> operator
};
void Output()
{
if (m_ptrEmployee == NULL) //Careful with comparisons. Always use ==, not =
cout << m_beginHour << "--" << "UNALLOCATED" << endl; //Operator << was the other way around. It's not >>, but << for cout
else
cout << m_beginHour << "--" << m_ptrEmployee->GetName() << endl;
}
void Reset()
{
m_ptrEmployee = NULL;
}
bool GetIsSet()
{
if (m_ptrEmployee != NULL)
return true;
else
return false;
}
private:
Employee* m_ptrEmployee;
int m_beginHour;
};