Re: string and class error
Wilson <tpwils@googlemail.com> wrote in message...
i have created a class which contains all the information needed for a
program based on accounts, this is shown below. When compiled the
string "word" (in function writetofile) which is initialised in the
constructor is apparently "undeclared", yet it has been declared in
the constructor.
No, you didn't! see below
i am new to c++ class programming, do i need to also declare it, as
well as initialise? and if not, what is the problem and how can it be
solved?
thanks, wilson
#include <iostream>
#include <fstream>
#include <time.h> // remove this, you are not using it.
#include <cstdlib> // remove this, you are not using it.
#include <cstring> // remove this, you are not using it.
using namespace std;
// if this is a header, remove that!!
class Account{
friend void new_account(); // ???
public:
Account(){string word = "hello";}
//can eventually be user inputted
Where did you declare/define 'string'?
Hint: #include <string>
Account( std::string mystr = "hello" ){
std::string word = mystr; // or: word( mystr );
} // 'word' disappears right here.
void returnbalance(){
std::cout << balance <<std::endl;
}
Bad name. If you say 'return', then return something.
float ReturnBalance() const { // should use 'double'
return balance;
}
// > void writetofile(){
// > string extension = ".txt";
// > ofstream writetofile;
// > writetofile.open((word + extension).c_str());
Note: 'word' is NOT defined here (it's not *in* your class).
void WriteToFile( std::string const &word ) /* const */ {
std::string filename( word );
filename += ".txt";
std::ofstream ofile( filename.c_str() );
if( not ofile.is_open() ){ /* error */ return;}
// > ofile << balance;
WriteTo( ofile ); // see below
WriteTo( std::cout ); // see below
}
void WriteTo( std::ostream &out ) /* const */ {
if( not out ){ /* error */ return;}
out << balance;
} // now you can 'print' to any std ostream obj.
void deposit(float amount){
balance = balance + amount;
std::cout << "$" << amount
<< " Has been deposited into your account";
std::cout << std::endl
<< "Your balance is now $" << balance;
}
virtual void withdraw(float amount){
if(amount < balance){
balance = balance - amount;
std::cout << "$" << amount
<< "has been withdrawn from your account";
std::cout << std::endl
<< "Your balance is now $" << balance;
}
else{
std::cout << std::endl
<<"Insufficient funds, your balance is $"<<balance;
}
}
float balance;
private:
int pin_number;
int account_number;
};
Don't hesitate to ask if you need more help.
[corrections always welcome.]
--
Bob R
POVrookie