2017-09-22 55 views
0

我想要设计类似于以下的类结构。主要想法是必须在需要时更新基类指针。同样,我们可以在子类上进行一些不相关的操作。如何让子类包含指向基类的指针

我想知道如何重新设计这个具有多态性和封装。这可能是一个很noob问题,但任何帮助表示赞赏。

我不关心被剪切的内存泄漏,因为在实际代码中使用了这些代码,因此正在使用删除来避免任何问题。

我想问的是,有没有类似于下面的类结构更好的方法,而不是Child1调用getBase来获取基类指针,它可以扩展基类,其中基类可能已经已经实例化,child1只是封装并提供一些功能。

class Base { 
private: 
    int a; 
    char b; 
public: 
    Base(int argA, char argB): a(argA), b(argB) { 
    } 


    char getChar() { 
     return b; 
    } 

    int getInt() { 
     return a; 
    } 

    void setChar(char foo) { 
     b = foo; 
    } 

    void setInt(int foo) { 
     a = foo; 
    } 
}; 

class Child1 { 
private: 

    Base *base; 
public: 
    Child1(PhysicalBlock *argBase) : base(argBase) { 

    } 

    Base *getBase() { 
     return base; 
    } 

    uint64_t getSum() { 
     int a = base->getInt(); 
     char b = base->getChar(); 
     return a + (int)b; 
    } 
}; 

class Child2 { 
private: 
    Base * base; 
    double c; 
public: 
    Child2(Base * argBase) : base(argBase), c(0.0) { 

    } 

    Base *getBase() { 
     return base; 
    } 

    double getDivision() { 
     int a = base->getInt(); 
     char b = base->getChar(); 

     return (double) ((double)a + (double)b)/c; 
    } 
}; 

int bla(Child1 * c1) 
{ 
    Base * b1 = c1->getBase(); 
    b1->setInt(55); 
    b1->setChar('z'); 
    return c1->getSum(); 
} 

int main() 
{ 
    Base * b1 = new Base(1, 'a'); 
    Base * b2 = new Base(2, 'b'); 

    Child1 * child1 = new Child1(b1); 
    Child2 * child2 = new Child2(b2); 

    bla(child1); 

    return 0; 
} 
+2

你为什么给我们展示'bla()'?哦,也许是这个'foo(child1);' - >'bla(child1);'?我也不明白你的问题。我的意思是我不认为你在问你的程序的内存泄漏... – gsamaras

+0

你真的*试图实现什么?这听起来有点像[XY问题](http://xyproblem.info)。 –

+0

@gsamaras已添加编辑。是的,这是一个错字。我指的是bla(child1) –

回答

0

我觉得你Child的意思是从base classderived class

class Base{ 
    // some stuff here 
}; 

class Child : public Base{ 
    // some code here 
}; 

现在孩子真Base类的孩子。小孩可以继承publicprivateprotected每一个都有其用处,所以在OOP章节继承中读一本有用的书。

  • 在我上面显示的示例中,您实现了Is-a relationship。所以你可以说: a man is a human, a dog is an animal...

  • 在你的例子中,你正在实现has-a relationship:所以在你的例子类Child has一个类的基类对象。你可以说'遏制。

  • 我不认为你需要在派生类中包含基类的对象。例如:

    class Base{}; 
    class Derived : protected Base{ 
        Base* pBase; // I don't think you need this. 
    }; 
    
  • 您可以访问基座部件(公共,保护)的形式导出,所以没有必要包含一个。

相关问题