missjohanna
missjohanna

Reputation: 303

C++ Need Solution for converting from const string

I have a (little) Problem. I was going to program a little string class in C++, which should allow you to use a string in the same way as a string in C#.

I wrote the following class:

class STRING
{
private:
  char * data;
  int length;

public:
  STRING();
  STRING(char * data);
  //string(char[] data, int length);

  void setData(char * data);

  int Length();
  char * toString();


  STRING operator = (STRING data);
  STRING operator = (char * data);
  STRING operator = (char data);
  STRING operator = (const string data);
  STRING operator + (STRING data);
  friend ostream& operator<<(ostream&os, const STRING& data);


  void display();


};

It is working. But I have one problem. If I try to initiate a new object of my class and want to set it with a value like:

STRING test1;
test1 = "TEST";

The compiler give me the following warning:
warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings] test1 = "TEST";

So I try to get a solution in form of an operation overloading. I tried this:

  STRING STRING::operator = (const string data)
  {
     char * tmp;
     int laenge;
     tmp = (char *) data
     laenge = strlen(tmp);
     this->data = new char[laenge + 1];
     this->length = laenge;

     strcpy(this->data, tmp);
  }

But it dont work and I'm out of ideas. Of cause it would work if I initiate it with:

STRING test1;
test1 = (char *) "TEST";

but my Dream is to use it like: STRING test1; test1 = "TEST"; or STRING test1 = "TEST";

Upvotes: 0

Views: 103

Answers (3)

Thomas Sparber
Thomas Sparber

Reputation: 2917

You Need an overloaded function for const char* but you can also use a template function which will be faster:

template<int length>
STRING STRING::operator = (const char (&s)[length])
{
    //resize or allocate data if needed
    strncpy(data, s, length);
}

Upvotes: 1

NathanOliver
NathanOliver

Reputation: 180585

You need an overload that takes a const char*

STRING STRING::operator = (const char* s)
{
    if (data != nullptr)
        delete [] data;
    length = strlen(s);
    data = new char[length + 1];

    strcpy(data, s);
}

Upvotes: 5

R Sahu
R Sahu

Reputation: 206577

You can change the argument types from char* to char const* in the following functions.

STRING(char * data);
STRING operator = (char * data);

Also, as a matter of general improvement, you can change

STRING operator = (STRING data);
STRING operator = (const string data);
STRING operator + (STRING data);

to

STRING& operator = (STRING const& data);
STRING& operator = (const string& data);
STRING operator + (STRING const& data) const;

See http://en.cppreference.com/w/cpp/language/operators why my suggested prototypes are more appropriate than what you have.

Upvotes: 0

Related Questions