我正在开发一个程序,它从现有文件中读取一些数据,将输入存储到istream
中,并将这些数据过滤到调用readDataFromFile()
方法的类的数据成员中。我有一个基类工作,我想扩展到派生类,并使用方法的重写来为派生类工作。我只是在努力从派生类访问基类的数据成员,因为基类不包含set
方法。
示例:
//has attributes x, y
class Base {
//declaration
virtual void readDataFromStream(istream&);
//definition
//function called from inside function that passes file data into stream
//- stream already contains data
void Base::readDataFromStream(istream& is) {
//insert values from stream into attributes
is >> x;
is >> y;
}
}
//inherits x, y
//has new attribute z
class Derived : Base {
//declaration
//method inherited from Base
virtual void readDataFromStream(istream&);
//definition - overrides definition in Base
//function called from inside function that passes file data into stream
//- stream already contains data
void Derived::readDataFromStream(istream& is) {
//insert values from stream into attributes
is >> x; <-- cannot access x to change value
is >> y; <-- cannot access y to change value
is >> z;
}
}
我正试图找到解决此问题的方法,但是没有看到它可以工作的方式,除非有某种方式将它们从流中读取到单个局部变量并且让对象重新通过它自己的自定义构造函数构建自己,虽然我以前从未见过它。
关于从这里去哪里的任何建议都会很棒,谢谢。
答案 0 :(得分:5)
您无法从派生类访问基类的私有成员。为此,您需要保护这些成员而不是私有成员:
class Base {
//no visibility defined means private, not visible for derived
int oops;
protected: // this is visible for derived, but not for outsiders
int x, y;
public: // this is visible for everyone
virtual void readDataFromStream(istream&);
};
另请注意,类继承中基类的默认可见性是私有的。这意味着派生类的用户原则上不能访问基类的公共成员(这里不是问题)。除非你有充分的理由不这样做,否则你宁愿公开继承。
class Derived : public Base { // no visibility would mean private inheritance
protected:
int z;
public:
void readDataFromStream(istream&) override;
};
最后,多态性不应该阻止你最大化封装和维护:
void Derived::readDataFromStream(istream& is) {
Base::readDataFromStream(is); // do base version
is >> z; // then do more specific things
}