Need help can't figure out why my header file function declarations won't work

时间:2015-10-30 22:16:36

标签: c++

cant figure out code. how do i make the PiggyBank& from my header work with my add functions in my cpp file?

Gives me error:

Error 6 error C2040: 'PiggyBank::addDimes' : 'void (int)' differs in levels of indirection from 'PiggyBank &(int)' h:\cosc1030\homework09\homework09\piggybank.cpp 36 1 Homework09

#ifndef PIGGYBANK_H
#define PIGGYBANK_H

#include <iostream>
using std::cout;
using std::endl;
class PiggyBank
{
public:
PiggyBank(int pennies, int nickels, int dimes, int quarters);

// Return the number of coins in the bank
int getPenniesCount() const;
int getNickelsCount() const;
int getDimesCount() const;
int getQuartersCount() const;

// Add coins to the bank
PiggyBank& addPennies(int p);
PiggyBank& addNickels(int n);
PiggyBank& addDimes(int d);
PiggyBank& addQuarters(int q);


// Withdraw coins from the bank, return number withdrawn
int withdrawPennies(int p);
int withdrawNickels(int n);
int withdrawDimes(int d);
int withdrawQuarters(int q);

void displayBalance() const;
void breakTheBank(); // Display the balance then cash out (all counts            zeroed).
private:
int pennies;
int nickels; 
int dimes;
int quarters;
};
#endif


#include "PiggyBank.h"
PiggyBank::PiggyBank(int pennies, int nickels, int dimes, int quarters)
{
addPennies(pennies);
addNickels(nickels);
addDimes(dimes);
addQuarters(quarters);
}

int PiggyBank::getPenniesCount() const
{
return pennies;
}
int PiggyBank::getNickelsCount() const
{
return nickels;
}
int PiggyBank::getDimesCount() const
{
return dimes;
}
int PiggyBank::getQuartersCount() const
{
return quarters;
}

void  PiggyBank::addPennies(int p)
{
    pennies = (p >= 0) ? p : 0;
}
void  PiggyBank::addNickels(int n)
{
    nickels = (n >= 0) ? n : 0;
}
void  PiggyBank::addDimes(int d)
{
    dimes = (d >= 0) ? d : 0;
}
void  PiggyBank::addQuarters(int q)
{
    quarters = (q >= 0) ? q : 0;
}

1 个答案:

答案 0 :(得分:1)

The header with PiggyBank& addDimes(int d); was provided,
so you'll need to change the void in the implementation to PiggyBank&.

What should be returned is likely to be the same object of which addDimes is called,
ie. this. this is a pointer, so return *this;.

Maybe you wonder what this is good for: Now you can write things like

functionWhichTakesaPiggyBank(myPiggyBank.addDimes(1)); //one line

myPiggyBank.addDimes(1).addDimes(1).addDimes(1); //chaining

etc.