Help with Class Accessors.
Feb 13, 2013 at 8:29am Feb 13, 2013 at 8:29am UTC
My current code is
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#ifndef SELLER_H
#define SELLER_H
//*****************************************************************
// FILE: Seller.h
// AUTHOR: Shaikh Omar
// LOGON ID: z1548925
// DUE DATE: 02/12/2012
//
// PURPOSE: Contains the declaration for the Seller class.
//*****************************************************************
class Seller
{
private :
char name[30];
double salesTotal;
public :
Seller(); //default contructor
Seller(char * newName, double newSalesTotal); //constructor for seller class
char getName(); //returns seller's name
double getSalesTotal(); //returns seller's sales total
void setSalesTotal(double newSalesTotal); //set the seller's sales total
void print(); //prints the saller's name and sales total
};
#endif
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
#include "Seller.h"
#include <iostream>
#include <iomanip>
using std::cout;
using std::string;
using namespace std;
Seller::Seller() //default contructor
{
*name = '\0' ;
salesTotal = 0;
}
Seller::Seller(char * newName, double newSalesTotal) //initializes the data members of the Selle$
{
strcpy (name, newName);
salesTotal = newSalesTotal;
}
char Seller::getName()
{
return * name;
}
double Seller::getSalesTotal()
{
return salesTotal;
}
void Seller::setSalesTotal(double newSalesTotal)
{
salesTotal = newSalesTotal;
}
void Seller::print()
{
cout <<left << setw(30) << name;
cout << right << setw (9) << salesTotal;
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#include <iostream>
#include "Seller.h"
using std::cout;
using std::endl;
int main()
{
// Test default constructor
Seller seller1;
// Test alternate constructor
Seller seller2("Jones, Martin" , 1234.56);
// Test print() method and whether constructors
// properly initialized objects
cout << "Printing seller1\n\n" ;
seller1.print();
cout << endl << endl;
cout << "Printing seller2\n\n" ;
seller2.print();
cout << endl << endl;
// Test accessor methods
cout << seller2.getName() << endl;
cout << seller2.getSalesTotal() << endl;
seller2.setSalesTotal(6543.21);
cout << seller2.getSalesTotal() << endl;
return 0;
}
I've gotten the program to work (for the most part) except I run into a problem with
cout << seller2.getName() << endl;
. When I try to get an output it only displays a J instead of the whole name. Any tips on how I could fix this?
Feb 13, 2013 at 8:41am Feb 13, 2013 at 8:41am UTC
Member function getName shall be declared as
const char * getName() const ; //returns seller's name
and defined as
1 2 3 4
const char * Seller::getName() const
{
return name;
}
Feb 13, 2013 at 8:54am Feb 13, 2013 at 8:54am UTC
Thank you very much. I didn't realized that I needed to put in the const char* instead of just char.
Topic archived. No new replies allowed.