问题描述
我有一个构造函数尝试初始化基类中的字段。编译器抱怨。该字段受保护,因此派生类应该具有访问权。
I have a constructor attempting to initialize a field in a base class. The compiler complains. The field is protected, so derived classes should have access.
//The base class:
class BaseClass
{
public:
BaseClass(std::string);
BaseClass(const BaseClass& orig);
virtual ~BaseClass();
const std::string GetData() const;
void SetData(const std::string& data);
protected:
BaseClass();
std::string m_data;
};
BaseClass::BaseClass(const std::string data) : m_data(data) { }
BaseClass::BaseClass() { }
BaseClass::BaseClass(const BaseClass& orig) { }
BaseClass::~BaseClass() { }
void BaseClass::SetData(const std::string& data)
{
m_data = data;
}
const std::string BaseClass::GetData() const
{
return m_data;
}
//The derived class:
class DerivedClass : public BaseClass
{
public:
DerivedClass(std::string data);
DerivedClass(const DerivedClass& orig);
virtual ~DerivedClass();
private:
};
DerivedClass::DerivedClass(std::string data) : m_data(data) { } //ERROR HERE
DerivedClass::DerivedClass(const DerivedClass& orig) { }
DerivedClass::~DerivedClass() { }
错误
DerivedClass.cpp:3:错误:类'DerivedClass'没有任何名为'm_data'的字段
DerivedClass.cpp:3: error: class ‘DerivedClass’ does not have any field named ‘m_data’
任何帮助是非常感谢。提前感谢。
Any help is greatly appreciated. Thank you in advance.
推荐答案
您不能在派生类构造函数中初始化m_data,而是将其作为参数传递给基类构造函数。
You cannot initialize m_data in the derived class constructor but instead pass it as an argument to the base class constructor.
这是: DerivedClass :: DerivedClass(std :: string data):BaseClass(data){}
这篇关于C ++:为什么我的DerivedClass的构造函数不能访问BaseClass的protected字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!