Using inheritance, derive twonew classes from the WCS_String class:UpperCaseStri
ID: 3856593 • Letter: U
Question
Using inheritance, derive twonew classes from the WCS_String class:UpperCaseString–This class will allow any characters to be stored but will store all alphabetic characters as upper case.DigitString–This class will allow only digits to be stored. Usage of other types of characters will cause anexceptionto be thrown.All error checking (bounds checking of indices, etc.) must be handled as exceptions (try, throw, catch). Your test program must demonstrate that all exception tests work.Create all members or friend functions deemed necessary for proper functioning of your classes.TO TURN IN:1)An electronic copy of the .cpp and .h files in the project folder as created by Visual Studio.
Explanation / Answer
main.cpp
#include <iostream>
using namespace std;
#include "UpperCaseString.h"
#include "digit_string.h"
void main ()
{
WCS_String S1 ("abcdef");
UpperCaseString U1;
UpperCaseString U2 (U1);
UpperCaseString U3 (S1);
UpperCaseString U4 (WCS_String ("abcd"));
digit_string s;
U3.Display ();
cout << endl;
U2 = U3;
U2 = S1;
U2 = "abcd";
if (U2.Compare (U3) == 0)
cout << "Same" << endl;
else
cout << "Different" << endl;
if (U2.Compare (S1) == 0)
cout << "Same" << endl;
else
cout << "Different" << endl;
U2.Display ();
cout << endl;
U2.Concat (S1);
U2.Display ();
cout << endl;
U2.SetAt ('x', 1);
U2.Display ();
cout << endl;
try { digit_string s( "1234X67" ) ; std::cout << s << ": ok " ; }
catch( const std::exception& e ) { std::cerr << "error: " << e.what() << ' ' ; }
try
{
digit_string s( "1234567" ) ; std::cout << s << ": ok " ;
s.SetAt( '9', 3 ) ; std::cout << s << ": ok " ;
s.SetAt( '@', 3 ) ; std::cout << s << ": ok " ;
}
catch( const std::exception& e ) { std::cerr << "error: " << e.what() << ' ' ; }
};
digit_string.h
#include <iostream>
#include <string>
#include <cctype>
#include <stdexcept>
#include "WCS_String.h"
using namespace std;
struct digit_string: public WCS_String
{
digit_string();
digit_string( const WCS_String & s ) : str(s) { are_digits(str) ; }
~digit_string();
bool SetAt( char c, std::size_t pos )
{
if( !std::isdigit(c) )
throw std::domain_error( WCS_String("non numeral character '") + c + "'" ) ;
else str.SetAt(pos, c);
return true ;
}
digit_string operator= ( const WCS_String& s ) { if( are_digits(s) ) str = s ; return *this ; }
friend inline std::ostream& operator<< ( std::ostream& stm, const digit_string& s )
{ return stm << s.str ; }
private:
WCS_String str ;
bool are_digits( const WCS_String& s )
{
for( char c = 0; c < strlen(s); ++c) if( !std::isdigit(c) )
throw std::domain_error( "non numeral in string '" + s + "'" ) ;
return true ;
}
};
#endif
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.