Str greeting = "Hello, " + name + "!";
where "name" is a Str, then I get a compilation error, saying "'operator +': 2 overloads have similar conversions, could be 'Str operator +(const Str &,const Str &)' or 'built-in C++ operator+(const char [8], int)'.#include <iterator>
#include <vector>
#include<iostream>
using namespace std;
class Str
{
private:
std::vector<char> data;
public:
typedef std::vector<char>::size_type size_type;
typedef std::vector<char>::iterator iterator;
typedef std::vector<char>::const_iterator const_iterator;
iterator begin() { return data.begin(); }
const_iterator begin() const { return data.begin(); }
iterator end() { return data.end(); }
const_iterator end() const { return data.end(); }
// default constructor must be defined explicitly, since non-default constructors are also defined
Str() { }
Str(const size_type n, const char c) : data(n, c) { }
Str(const char* cp)
{
std::copy(cp, cp + std::strlen(cp), std::back_inserter(data));
}
// Since this is a template, the iterators can be anything: pointers in an array of chars, std::vector<string> iterators, std::std::vectortor<string> iterators, std::list<string> iterators, etc.
template <class In> Str(In b, In e)
{
std::copy(b, e, std::back_inserter(data));
}
char& operator[](size_type i) { return data[i]; }
const char& operator[](size_type i) const { return data[i]; }
Str& operator+=(const Str& s)
{
std::copy(s.data.begin(), s.data.end(), std::back_inserter(data));
return *this;
}
size_type size() const
{
return data.size();
}
// conversion operators
operator std::vector<char>() const;
operator bool() const;
template <class In> void insert(iterator dest, In b, In e)
{
data.insert(dest, b, e);
}
};
Str operator+(const Str& s1, const Str& s2)
{
Str s = s1;
s += s2;
return s;
}
Str::operator std::vector<char>() const
{
std::vector<char> ret = data;
return ret;
}
Str::operator bool() const
{
if (data.size() > 0)
return true;
return false;
}
int main()
{
Str name = "Joe";
Str greeting = "Hello, " + name + "!";
return 0;
}
Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.
”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.
Our community of experts have been thoroughly vetted for their expertise and industry experience.
The Distinguished Expert awards are presented to the top veteran and rookie experts to earn the most points in the top 50 topics.