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


Автор: Redstuff 3.6.2006, 19:13
Над объектом "строка" реализовать следующий набор операций:
+ присоединение строки в конец,
- вырезание подстроки из строки,
^ получение позиции подстроки в строке,
! переворачивание строки,
= присваивание,
>> загрузить строку из файла и ввести с консоли,
<< сохранить строку в файле и вывести на консоль.
Сделать несколько конструкторов объекта.
 

реализовать в консоли. 

Автор: Redstuff 4.6.2006, 12:20
Код

#include <stdio.h>
#include <iostream.h>
#include <conio.h>
#include <string.h>
#include <mbstring.h>
#pragma hdrstop
#pragma argsused
class String {
  private:
  char* s;
  public:
  String& operator+(const String&) const;
};
String& String::operator+(const String& s1) const {
  char* s2 = new char[strlen(s1.s) + strlen(s) + 1];
  strcat(s2, s1, s);   // выдает сообщение об ошибке
  String newStr(s2);
  delete s2;
  return newStr;
}

int main(int argc, char* argv[]) {
  String s1="Hello";
  String s2="Goodbye";
  String s3=s1+s2;
  cout<<s3;
  getch();
}
 

Автор: Mal Hack 4.6.2006, 13:26
http://forum.vingrad.ru/index.php?showtopic=96055&hl= 

Автор: Oleg_Ci 4.6.2006, 13:47
Код

#include <stdio.h>    
#include <iostream>    
#include <conio.h>    
#include <string.h>    
#include <mbstring.h>    
//#pragma hdrstop    
//#pragma argsused

class String {    
  public:    
      char* s;        //    Public !!!
  String & operator+(const String&) const;
  String ( char *c ) { s = c ;}
  void newStr (char *c){    s = c; }
};    

String & String::operator+(const String& s1) const {    
  char* s2 = new char[strlen(s1.s) + strlen(s)];    // +1 было ??
  strcpy(s2,this->s);
  strcat(s2, s1.s);   // выдает сообщение об ошибке
  String newStr(s2);    
  //delete s2;        // ЗАЧЕМ ?
  return newStr;    
}    

int main(int argc, char* argv[]) {    
  String s1="Hello";    
  String s2="Goodbye";    
  String s3=s1+s2;    
  std::cout<<s3.s;    
  //getch();    
  std::cin.get();
  return 0;
}
 
Microsoft VS 2003 

Автор: Redstuff 4.6.2006, 13:48
Mal Hack спасибо за ссылку на тему, но уж больно все СЛОЖНО. Я эту тему ваще не понимаю пока. Хотелось бы пример попроще.

Добавлено @ 14:01 
Код

 #include <stdio.h>
#include <iostream.h>   // <iostream> приходится писать std::cin(cout)
#include <conio.h>    
#include <string.h>    
#include <mbstring.h>    
//#pragma hdrstop    
//#pragma argsused

class String {    
  public:
      char* s;        //    Public !!!
  String & operator+(const String&) const;
  String ( char *c ) { s = c ;}
  void newStr (char *c){    s = c; }
};    

String& String::operator+(const String& s1) const {
  char* s2 = new char[strlen(s1.s) + strlen(s)];    // +1 было ??
  strcpy(s2,this->s);
  strcat(s2, s1.s);
  String newStr(s2);
  //delete s2;        // Зачем ?
  return newStr;      // Теперь тут ошибка: Attempting to return a reference
                      // to local variable 'newStr'
}

int main(int argc, char* argv[]) {    
  String s1="Hello";    
  String s2="Goodbye";    
  String s3=s1+s2;
  cout<<s3.s;          //без std:: т.к. <iostream.h>
  //getch();
  cin.get();
  return 0;
}
 
 

Автор: Mal Hack 4.6.2006, 14:24
Цитата(Redstuff @  4.6.2006,  13:48 Найти цитируемый пост)
Mal Hack спасибо за ссылку на тему, но уж больно все СЛОЖНО.

Там есть варианты и по сложнее smile 

Автор: Oleg_Ci 4.6.2006, 17:19
Код

#include <vcl.h>
#include <stdio.h>
#include <iostream.h>   // <iostream> ïðèõîäèòñÿ ïèñàòü std::cin(cout)
#include <conio.h>
#include <string.h>
#include <mbstring.h>
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused

class String2 {
  public:
  char* s;        //    Public !!!
  String2  operator+ (const String2 & s1)const;
  String2 ( char *c ) { s = c ;}
  String2  operator = ( String2 & s33 );
  ~String2(){ delete s; }
};

String2  String2::operator+(const String2 &s1)const
{

  char *s22 = new char[strlen(s1.s)+strlen(this->s)+1];// +1 ïðàâèëüíî áûëî
  strcpy(s22,this->s);
  strcat(s22, s1.s);

  String2 *newStr = new String2(s22);// с этот указатель удалить надо где-то 
  //delete s22;
  return *newStr;      // Òåïåðü òóò îøèáêà: Attempting to return a reference
                      // to local variable 'newStr'
}
String2  String2::operator= ( String2 & s33 )
{
   strcpy(s,s33.s);
   return *this;
}

int main(int argc, char* argv[]) {
  String2 s1="Hello";
  String2 s2="Goodbye";
  //s2=s1;
  String2 s3=s1+s2;
  cout<<s3.s;          //áåç std:: ò.ê. <iostream.h>
  //getch();
  cin.get();
  return 0;
}
//---------------------------------------------------------------------------

Цитата
String2 *newStr = new String2(s22);// с этот указатель удалить надо где-то

C++ Builder 6 . C указателем не пойму что делать, а так работает. 

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