Re: Converting C to C++
In article <1148511337.722910.174590@j73g2000cwa.googlegroups.com>,
fakeprogress@gmail.com wrote:
How would I go about converting this C code to C++?
/* LIBRARY is an array of structures */
/* This function compares 'tcode' with */
/* existing codes in the array. */
/* It returns the index of the code in */
/* the LIBRARY structure if it is found. */
int findcode( LIBRARY *b, int n, char *tcode ) {
int i;
for( i = 0; i < n; i++ )
if( strcmp( b[i].code, tcode ) == 0 )
return i;
return -1;
}
(I just need to know if the code exists [ie, function returns 1] in the
class. Indeces are not necessary.)
// Libraries hold more than just books, but everything a
// library holds must have a code associated with it.
class Resource
{
string code;
public:
Resource( string code_ ): code( code_ ) { }
virtual ~Resource() { }
const string& getCode() const { return code; }
};
struct has_code : unary_function<Resource, int>
{
string code;
has_code( const string& code_ ): code( code_ ) { }
bool operator()( const Resource& resource ) const {
return resource.getCode() == code;
}
};
class Library
{
vector<Resource> resources;
public:
bool codeExists( const string& tcode ) const {
return find_if( resources.begin(), resources.end(),
has_code( tcode ) ) != resources.end();
}
};
class Book : public Resource
{
// add whatever here
};
This is what I have:
class Book {
private:
std::string author;
std::string title;
std::string code;
int ncopies;
int onloan;
public:
Book( const std::string &auth, const std::string &tit,
const std::string &cd, int ncop, int nonloan );
Book( const std::string &auth, const std::string &tit,
const std::string &cd, int ncop );
const std::string &getAuthor( ) const;
const std::string &getTitle( ) const;
const std::string &getCode( ) const;
int getNcopies( ) const;
int getOnLoan( ) const;
void Borrow( int qty );
void nReturn( int qty );
};
typedef std::vector<Book> Library;
I am inclined to make Library a full fledged class...
int findcode( Library &lib, std::string tcode ) {
for( Library::iterator itor = lib.begin( ); itor != lib.end( );
++itor ) {
Book &b = *itor;
if( ( tcode.compare( b.getCode ) ) == 0 )
return 1;
}
return -1;
}
bool findcode( const Library& lib, const string& tcode )
{
for (Library::const_iterator it = lib.begin(); it != lib.end(); ++it)
if ( it->getCode() == tcode )
return true;
return false;
}
(a) If all you need to know is if something with the code 'tcode'
exists, then return a 'bool' instead of an 'int'.
(b) You don't need to cast the '*itor' into a 'Book&'
(c) You don't need to use the 'compare' member-function, simply compare
them with operator==.
(d) 'b.getCode' needs parens after it... 'b.getCode()'