I'm trying to create a custom string class using std::vector< char >.
Please take a look at my code below.
#include <iostream>
#include <vector>
class mString {
public:
mString();
explicit mString(const char *str);
mString(const mString &str);
mString operator=(const char *str);
private:
typedef std::vector<char> vecChar;
vecChar _vc;
};
inline mString::mString(){}
inline mString::mString(const char *str) {
const vecChar::size_type size = strlen(str);
_vc = vecChar(str, str + size);
}
inline mString::mString(const mString &str) {
_vc = str._vc;
}
inline mString mString::operator=(const char *str) {
const vecChar::size_type size = strlen(str);
_vc = vecChar(str, str + size);
return *this;
}
int main(int argc, const char * argv[]) {
/* This works */
mString a;
a = "Hello World";
/* Error : No viable conversion from 'const char[12]' to mString */
mString b = "Hello World";
return 0;
}
I don't understand why 'mString b = "Hello World";' doesn't work while 'mString a; a= "Hello World";' works. What do I need to do in order to make it work?
Thank you in advance!
This has nothing common with the assignment operator.
You declared this constructor
explicit mString(const char *str);
with the function specifier explicit
.
Thus in this declaration
mString b = "Hello World";
the constructor can not be called to convert the string literal "Hello World"
to an object of the type mString
.
Remove the function specifier explicit
and the declaration will compile.
Or instead of the copy initialization as in the declaration above you could use the direct initialization like
mString b( "Hello World" );
So in this declaration
mString b = "Hello World";
there are used constructors. But in this expression statement
a= "Hello World";
there is indeed used the assignment operator.