Jump to content

sobrecarga de operator[]


Recommended Posts

Posted

alguem poderia me dizer pq isso nao funciona ?!

class String
{
      char* buffer;
      // mais codigos ...
      char operator []( int k ) const
      {
            return buffer[k];
      }
}

class Match
{
      String* text;
      Match( const String& str ):
            text( new String( str ) )
      {}
      // mais codigos ...
}

int main()
{
      String str( "texto" );
      Match txt( str );

      printf( "%c" , txt.text[0] );
}

no compilador aparece isso ( uso o Dev-C++ )

52 E:\Nova Pasta\prog\c - c++\ProgII\collection\MatchMain.cpp [Warning] cannot pass objects of non-POD type `class String' through `...'; call will abort at runtime

vlw ..

Posted

Dá-me a sensação de que é um trabalho de casa e não está a invocar o operador. O C++ não pode ser aprendido a "sentimento" e a "testar".  Descarrega ou compra um livro. printf e outras funções do C, falta de âmbitos nas classes, etc indicam que deve estudar primeiro.

Não tenho  muito tempo, mas alterei o teu "código" e funciona:

#include<iostream>
using namespace std;
class String
{
public:
  char* buffer;
  String(char* rhs):buffer(rhs){}
  String(String * rhs):buffer(rhs->buffer){}
  const char& operator []( int k ) const
  {
    return buffer[k];
  }
};
class Match
{
public:
      String* text;
      Match( const String& str ):text( new String( str ) )
      {}
      // mais codigos ...
};

int main()
{
      String str("texto");
      Match txt( str );
      cout<<str.buffer<<endl;
      cout<<txt.text->buffer<<endl;

}
Posted

intendi o problema ..

o caso e' q eu impletei os codigo em String.cpp .. e com o famoso ctrl+c - ctrl+v foi o inline junto  ?

q criava problema qdo feito assim

String str( texto );
printf( "%c" , str[0] );

ja' no caso de Match .. text e' um ponteiro entao o certo seria ..

Match txt( texto );
printf( "%c" , (*txt.text)[0] );

certo .. obrigado ..  😉

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.