所以我有这个:
class myString : public std::string{
public:
void translate(){
std::string phrase = blarg;
... Code ...
blarg = phrase;
}
现在,我知道它不是blarg,但是我需要在这里访问与myString字符串继承关联的字符串?
除此之外,我可以这样做:
myString phrase;
phrase = "Roar";
那么如何访问" Roar"在我的功能?
一切都包括在内。
答案 0 :(得分:0)
只需使用this
指针访问该对象。
class myString : public std::string
{
public:
void translate()
{
std::string phrase = *this;
/*
... Code ...
*/
*static_cast<string*> (this) = phrase;
}
}
答案 1 :(得分:0)
你不应该这样做。
但这是代码
#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
}