samedi 29 février 2020

How can i link the vector elements to a pointer

I need help in the class design workflow with the following functionality.

I have a class with the name of Stage the stage has a variable of class Director as vector and i would want to point to these data elements of the vector from another class Channel.

class Stage
{
private:
    int time;
    std::vector<Director> directors;
public:
    Stage()
    { }
    void AddDirector(Director director)
    {
        directors.push_back(director);
    }    
    Director* GetDirector(int index)
    {
        return &directors[index];
    }    
    void DeleteDirector(std::string dirName)
    {
        // remove the director from the vector which matches the name of the input string
    } 
};

////////////////////////////////////////////////////////////////////////////////////////////////

class Director
{
private:
    int time;
    std::string stdstrDirName;
public:
    Director()
    { }
    std::string GetName()
    {
        return stdstrDirName;
    }
    void SetName(std::string name)
    {
        stdstrDirName = name;
    }

   // GetTime and SetTime

};




 class Channel
{
private:
    int time;
    std::string stdstrChannelName;
    Director* dir;
public:
    Channel()
    { }
    std::string GetName()
    {
        return stdstrChannelName;
    }
    void SetName(std::string name)
    {
        stdstrChannelName = name;
    }

    std::string  GetDirectorName()
    {
        dir->GetName();
    }

    void SetDirector(Director* director)
    {
        dir = director;
    }

};

This is how i would point them.

int main()
{
    Stage stage;  // Create Stage Object
    Director d1, d2, d3; // Create Director Objects
    Channel channel;
    d1.SetName("D1"); d2.SetName("D2"); d3.SetName("D3");
    stage.AddDirector(d1); stage.AddDirector(d2); stage.AddDirector(d3);
    channel.SetDirector(stage.GetDirector(1)); // Link Director to Channel
}

This approach has a drawback whenever the vector gets resize the pointers in the Channel will not hold reference to their valid object.

I need help in what should be the design of the class structure ?

Aucun commentaire:

Enregistrer un commentaire