将基类的对象扩展为复杂类的对象

时间:2011-10-18 14:26:52

标签: c++ oop

我该怎么做?我想到了复杂类中的一个方法,它将基本对象的每个变量复制到复杂对象,但这看起来有点不方便。

class Basic
{
  //basic stuff
}

class Complex : public Basic
{
  //more stuff
}

Basic * basicObject = new Basic();
//now "extending" basicObject and "cast" it to Complex type
//which means copy everything in basicObject to an complexObject

或类似的东西:

Complex * complexObject = new Complex();
complexObject.getEverythingFrom(basicObject);

似乎太不方便了,因为每次我更改Basic类时,我都必须更改这个“复制”方法。

2 个答案:

答案 0 :(得分:1)

定义要在受保护部分中的类之间共享的值,如下所示:

class Base
{
public:
int myPublicShared1;
int myPublicShared2;

Base& operator = (Base& other)
{
    // Copy contents in base across
    return *this;
}
protected:
int myShared1;
int myShared2;

private:
int notShared1;
int notShared2;
};

class Derived : public Base
{
public:
Derived& operator = (Derived& other)
{
    Base::operator = (other);
    // copy the rest of variables specific to Derived class.
}
Derived& operator = (Base& other)
{
    Base::operator = (other);
}
// Derived now has all variables declared in Base's public and protected section
};

答案 1 :(得分:0)

在C ++中,对象无法更改其类型。

因此,您要么立即重写程序来创建Complex个对象,要么创建一个副本ctor,以便您可以这样做:

new Complex(* basicObject);

旁注:从像extend这样的词和新的用法看起来你来自java世界。不要错误地认为你在java中做的事情也是你在C ++中的表现。