Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > C/C++: Общие вопросы > Помогите с кодом


Автор: Hawaii 11.7.2007, 01:50
Код

// strimem.cpp
// memory-saving String class
// overloaded assignment and copy constructor
#include <iostream>
#include <cstring>                //for strcpy(), etc.
using namespace std;
class String;
////////////////////////////////////////////////////////////////
class strCount                    //keep track of number
   {                              //of unique strings
   private:
      int count;                  //number of instances
      char* str;                  //pointer to string
      friend class String;        //make ourselves available
      //member functions are private 
      strCount(char* s)           //one-arg constructor
         {
         int length = strlen(s);  //length of string argument
         str = new char[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        
   };
////////////////////////////////////////////////////////////////
class String                      //String class
   {
   private:
      strCount* psc;              //pointer to strCount
   public:
      String()                    //no-arg constructor
         { psc = new strCount("NULL"); }
      String(char* s)             //1-arg constructor
         { psc = new strCount(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                     //   otherwise,
            (psc->count)--;       //   decrement its count
         }
      void display()              //display the String
         {
         cout << psc->str;                 //print string
         cout << " (addr=" << psc << ")";  //print address
         }
      void operator = (String& S) //assign the string
         {
         if(psc->count==1)        //if we are its last user,
            delete psc;           //   delete our strCount
         else                     //   otherwise,
            (psc->count)--;       //   decrement its count
         psc = S.psc;             //use argument's strCount
         (psc->count)++;          //increment its count
         }
   };
////////////////////////////////////////////////////////////////
int main()
   {
   String s3 = "When the fox preaches, look to your geese.";
   cout << "\ns3="; s3.display();   //display s3

   String s1;                       //define String
   s1 = s3;                         //assign it another String
   cout << "\ns1="; s1.display();   //display it

   String s2(s3);                   //initialize with String
   cout << "\ns2="; s2.display();   //display it
   cout << endl;
   return 0;
   }



Автор: archimed7592 11.7.2007, 02:09
Hawaii, какую ошибку? На какой строке? Или ты считаешь, что сейчас все бросятся к своим компиляторам, чтобы узнать какую ошибку выдаёт и помочь тебе?

Автор: Hawaii 11.7.2007, 02:15
Строка в main() 
Код
   String s3 = "When the fox preaches, look to your geese.";



Добавлено через 2 минуты и 40 секунд
Пишет это: 
Код
In function `int main()':
no matching function for call to `String::String(String)' 
candidates are: String::String(String&) 
   String::String(char*)  
initializing temporary from result of `String::String(char*)' 


Автор: jonie 11.7.2007, 02:39
интересный комплятор...
и прописать явно String::String(const char* const) попробывать ?
ну и конструктор копирования пишется так String(const String& S);

и это "{ psc = new strCount(s); }" думаешь сработает?) у меня есть дикие сомнения....(сработать то сработает, а вот не скопирует вроде)

Автор: Hawaii 11.7.2007, 03:18
В учебнике этот код написан. Но на компе он не работает. Абалдеть...
jonie, чё та я не врубаюсь, кекой меседж ты мне хочешь донести ??? Код не я писал, и я не думаю, сработает ли у меня { psc = new strCount(s); } или нет.

Автор: bsa 11.7.2007, 10:26
Измени конструкторы на:
Код
strCount(const char* s)
String(const char* s)
String(const String& S)

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)