英文:
How can I access a protected variable in child class through an abstract class pointer?
问题
以下是您要翻译的部分:
"How can we access 'pencil' in 'youngWriter' class through 'artist'?"
"如何通过 'artist' 在 'youngWriter' 类中访问 'pencil'?"
英文:
I have an abstract class that I have derived from two child classes. One of them has a protected variable that the other one does not. To make the code more general, I have to use an smart pointer of the abstract class. Is there any way to access the protected variable through the pointer? As an example, Consider the following code (the real code is huge and I had to write this sample code):
class Pen{
public:
pen(string _color): color(_color){};
getColor(){return color;};
protected:
string color;
};
// base abstract class
class writer{
public:
writer() {}
virtual changeColor(string color) = 0;
};
class oldWriter: public writer{
protected:
Pen *pen;
public:
oldWriter(string _pen):
pen(_pen){}
virtual changeColor(string color){ pen->color = color;};
};
class youngWriter: public writer{
protected:
Pen *pen;
Pencile pencil; //we need to have access to pencil
public:
youngWriter(string _pen):
pen(_pen){}
virtual changeColor(string color){ pen->color = color;};
Pencil getPencil(){return pencil;};
};
int main(){
unique_ptr<Writer> artist;
Pencil pencil = artist->getPencil(); //how?
}
How can we access "pencil" in "youngWriter" class through "artist"?
答案1
得分: 1
如果我理解代码正确,问题与名为"Writer"的类有关,该类没有一个名为getPencil的方法。getPencil是"youngWriter"类的一个方法。因此: 1) artist必须是youngWriter的一个实例。 2) Writer必须包含一个抽象方法getPencil。
英文:
if i well understood the code, the problem is related to class "Writer" which haven't a method called getPencil.
getPencil is a method of class youngWriter.
Therefore:
- artist have to be a youngWriter instance.
- Writer have to contains a method getPencil abstract.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论