I inherited some code that uses the class adapter pattern and I want to convert it to use the object adapter pattern.
The custom class string
is adapting std::string
, and it's in the MyString
namespace.
Here's a snippet of how the code looks before I alter it.
// mystring.h
namespace MyString
{
// StringInterface is the new (abstract) interface that the client will use.
// Inheriting the implementation of std::string to build on top of it.
class string : public StringInterface, private std::string
{
...
};
}
// mystring.cpp
namespace MyString
{
...
string& MyString::string::operator=(const string& s) // copy assignment operator
{
if (this != &s) std::string::operator=(s);
return *this;
}
...
}
Once I remove the private inheritance of std::string
(which I do because--correct me if I'm wrong--the object adapter pattern uses composition and not inheritance of the implementation), the statement std::string::operator=(s);
causes the error " call to non-static member function without an object argument ".
So I'm not really sure how to accomplish this. It's my first time dealing with the adapter pattern (and C++ isn't my strongest language); maybe I'm overlooking something simple.
So assuming you have made the std::string
a member of your class
class string : public StringInterface
{
...
std::string m_str;
...
};
you should then modify all your operations on the once "inherited" (but it's privately... well) std::string
to your now member std::string
, which in my example, is m_str
. For example, instead of doing std::string::size()
, you should do m_str.size()
.
For your operator=()
, you should then do it this way:
string& MyString::string::operator=(const string& s) // copy assignment operator
{
if (this == &s) return *this; // So you'll only have to do this test once
m_str = s.m_str; // instead of std::string::operator=(s);
// ...
return *this;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.