Strange assignment problem - C++
Having a strange problem making a new string class and assigning an array of char*
to it in the GCC compiler. Source code:
#include "../Include/StdString.h"
StdString::StdString()
{
//ctor
internstr = std::string();
}
char* StdString::operator=(StdString other) {
return other.cstr();
}
StdString StdString::operator+(StdString other) {
StdString newstr = StdString();
newstr.internstr = internst开发者_如何转开发r+other.internstr;
return newstr;
}
void StdString::operator=(char* other) {
internstr = other;
}
StdString::~StdString()
{
//dtor
}
char* StdString::cstr() {
return (char*)internstr.c_str();
}
Error: conversion from char*
to non-scalar type StdString
requested.
How did std::string
do their assignments?
std::string can do its conversion because it defines a conversion constructor. Something like this.
class std::string {
// ...
std::string(const char *);
};
NOTE: the actual std::string is more complicated.
With the assignment operator you should be able to do
StdString str;
str = "hello";
but not
StdString str = "hello";
StdString mystr = "Hello world!";
requires copy constructor.
Try to add the following:
StdString::StdString(const char* other)
{
internstr = other;
}
The error you're having is for not providing a constructor that takes a char*
. This is the conversion function the compiler complains about for being missing.
StdString::StdString(char const* s)
{
// ...
}
Also, if your internal string is a std::string
then you don't need any of the assignment operators, copy constructor and destructor. Once you add the char*
conversion constructor the compiler-provided assignment operator will magically work for char*
as well. Well, not really magically: the compiler will see that it can convert a char *
to a StdString
through your conversion constructor, and then use that with the implicit assignment operator.
You can also leave the default constructor's definition empty; this will give you the default construction for all members, which is probably good enough.
Looks like you are confusing assignment and initialization. Initialization uses a constructor, even when it's called with a "=" symbol.
Why do you define your conversion operator as:
char* StdString::operator=(StdString other)
{
return other.cstr();
}
All this does return the contents of other
without setting the current class's internstr
to that given by other.
What I would do would look more like:
StdString& StdString::operator=(StdString other)
{
// copy contents of other to this->internstr
return *this;
}
精彩评论