如何通过抽象类指针访问子类中的受保护变量?

huangapple go评论60阅读模式
英文:

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:

  1. artist have to be a youngWriter instance.
  2. Writer have to contains a method getPencil abstract.

huangapple
  • 本文由 发表于 2023年2月8日 22:07:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75386937.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定