Поэтому у меня есть следующее:
class myString : public std::string{
public:
void translate(){
std::string phrase = blarg;
... Code ...
blarg = phrase;
}
Теперь я знаю, что это не blarg, но что я должен был бы здесь, чтобы получить доступ к строке, связанной с наследованием строки myString?
В основном за пределами этого я мог бы сделать:
myString phrase;
phrase = "Roar";
Итак, как мне получить доступ к "Roar" в моей функции?
Все включено правильно.
Просто обратитесь к объекту с помощью this
указателя.
class myString : public std::string
{
public:
void translate()
{
std::string phrase = *this;
/*
... Code ...
*/
*static_cast<string*> (this) = phrase;
}
}
myString::myString(std::string const & ref) : std::string(ref) { }
Вы не должны это делать.
Но вот код
#include <iostream>
#include <string>
#include <vector>
class myString : public std::string{
public:
using std::string::string; // inheriting the constructors from std::string
void translate(){
// 'std::string phrase = *this' won't work because no such constructor takes 'myString' exist
std::string phrase(this->c_str(), this->length());
phrase += "2";
// operator= won't work because type doesn't match
// it is expecting 'myString' type but not 'std::string'
this->assign(phrase); // use assign instead of operator=
}
};
int main()
{
myString m = "test";
std::cout << m << '\n'; // test
m.translate();
std::cout << m << '\n'; // test2
}
std::string phrase = *this;
?