Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialize own String class by assignment in c++

Tags:

c++

string

class

I'm writing my own string class StringEx in c++ (don't worry, just for exercise) but I'm failing at creating an instance of my class by assigning a string to it:

StringEx string1 = StringEx("test"); // works fine
StringEx string2 = "test"; // doesn't work

string string3 = "test";
string1 = string3; // also works fine

I overloaded the assignment operator so it can handle with std::string but I have to create an object of StringEx first.

How can I create a new object of StringEx by assigning a string to it? Is it even possible to get c++ handling every "string" as an object of my StringEx class?

This is my StringEx.h which works now

#ifndef STRINGEX_H
#define STRINGEX_H


#include <iostream>
#include <string>
#include <vector>
using namespace std; //simplyfying for now

class StringEx
{
private:
    vector<char> text;
public:
    StringEx();
    StringEx(string);
    StringEx(const char*);  // had to add this
    StringEx(vector<char>);

    int size() const;
    int length() const;
    char at(int) const;

    void append(const string&);
    void append(const StringEx&);
    void append(const char*);  // had to add this

    StringEx operator+(const string&);
    StringEx operator+(const StringEx&);
    StringEx operator+(const char*);  // had to add this too

    StringEx operator=(const string&);
    StringEx operator=(const StringEx&);
    StringEx operator=(const char*);  // had to add this too

    StringEx operator+=(const string&);
    StringEx operator+=(const StringEx&);
    StringEx operator+=(const char*);  // had to add this too

    friend ostream& operator<<(ostream&, const StringEx&);
};

#endif // STRINGEX_H
like image 903
SimonH Avatar asked Nov 16 '25 05:11

SimonH


1 Answers

A few precisions:

StringEx string1 = StringEx("test"); // works fine

This use the copy-constructor, i.e. StringEx(const StringEx& other);

StringEx string2 = "test"; // doesn't work

This tries to use a constructor with the following signature: StringEx(const char* str);

Finally, those two lines:

string string3 = "test";
string1 = string3; // also works fine

create an std::string from a const char*, which the standard library defines, and then use the copy-assignment operator overloaded for std::string that you seem to have defined correctly, i.e. StringEx& operator=(const std::string& other).

The key point here is that this statement:

Type myVar = something;

is not an assignement, it's an declaration and initialisation of a variable which uses a constructor, not the copy-assignment operator.

In your case, you're just missing a constructor that takes a const char* as parameter.

like image 140
JBL Avatar answered Nov 18 '25 17:11

JBL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!