c++: ‘std::__cxx11::string abc::m_string’ is protected within this context
错误
]oot@rhel-cleanmodules:~/mzhan017/test/c++[root@rhel-cleanmodules c++]# g++ string.cpp
string.cpp: In function ‘int main()’:
string.cpp:17:3: error: ‘std::__cxx11::string abc::m_string’ is protected within this context
a.m_string="age";
^~~~~~~~
string.cpp:6:9: note: declared protected here
string m_string;
原因
成员 m_string 被protected 修饰;
解决方法
- 将使用m_string的函数,变成friend 函数;
- 添加set 函数,给m_string 赋值。
代码
#include <iostream>
using namespace std;
int main();
class abc
{
//friend int main();
protected:
string m_string;
public:
string get();
};
string abc::get()
{
return m_string;
}
int main()
{
abc a;
a.m_string="age";
const char *abc = a.get().c_str();
cout<< abc<<endl;
}