I am following fairly old book for my course and I have problem with one of the examples from the book. It does not compile and gives me bunch of errors.
I am not sure how to fix this to get this as working example. Could you suggest
workaround?
thanks :)
#include <iostream>
#include <cstring> // sor strcpy()
class strCount // keep track of number of unique strings
{
private:
int count; // number of instances
char* str; // Pointer to string
friendclass String; // allows access to the class from class String
// members functions are private
strCount( constchar* s ) // strCount(char* s) // one argument constructor
{
int length = strlen(s); // length of string argument
str = newchar[length+1]; // get memory for string
strcpy(str, s); // copy argument to it
count = 1; // start count at 1
}
~strCount() // destructor
{
delete[] str; // delete the string (pointer)
}
};
class String
{
private:
strCount* psc; // pointer to strCount
public:
String() // no argument constructor
{
psc = new strCount("NULL");
}
String(constchar* s) // String(char* s) // 1 argument constructor
{
psc = new strCount(s);
}
String( const String& S ) // String(String& S) // copy constructor
{
psc = S.psc;
(psc->count)++;
}
~String() // destructor
{
if(psc->count==1) // if we are its last user
delete psc; // delete our strCount
else
(psc->count)--; // decrement its count
}
void display() // display string
{
std::cout << psc->str; // print string
std::cout << " (address= " << psc << ")"; // print address
}
voidoperator = (String& S) // assign the string
{
if(psc->count==1) // if we are its last user
delete psc; // delete our strCount
else
(psc->count)--; // decrease its count
psc = S.psc; // use arguments strCount
(psc->count)++; // increment its count
}
};
int main() {
String s3 = "When the fox preaches, look to your geese";
std::cout << "\ns3 = ";
s3.display();
String s1;
s1 = s3;
std::cout << "\ns1 = ";
s1.display();
String s2(s3);
std::cout << "\ns2 = ";
s2.display();
std::cout << std::endl;
system("pause");
}
Consider throwing this book away; it would do more harm than good.
The deprecated conversion from string literal to char* was removed in C++11,
but the code was not const-correct even in legacy C++
I was worried about this book, however it has its positive sides (apart from stuff that is not outdated) it keeps me on my toes and questions many things in the book (that is the reason I ask so many questions here)
I found plenty of typos (my tutor is on verge or exploding ;) each week I show him one I found during my week reading.)
However I am struggling to find book about C++ that would be up to date let say up to c++14 and as comprehensive and rich in example and tests. This book is a brick over 1000 pages and in most of the time I have full programs with code I can run and play with.
------------------------------------------------------------------------------------------------
Update: it is running now! thank you :) I will play with this code today