记忆共享;遗产;基础和派生实例; C ++

时间:2013-03-29 17:28:26

标签: c++ memory inheritance sharing

好的,这个例子对于我想要理解的概念非常简单。我只会告诉你代码:

class Base
{
protected:
    string name;
public:
    virtual string getName() const { return this->name; }
    virtual void setName(string name) { this->name = name; }
....
}

class Derived : public Base
{
private:
    double price;
....
}

main(int argc, char** argv)
{

    Base* base = new Base("Base Class");
    Derived* derived = new Derived(base, 453.21);
    derived->setName("Name changed!");

    cout << "Name of instance: " << base->getName() << endl;

    // Desired effect
        Output: 'Name changed!'
    // Actual effect
        Output: 'Base Class'
....
}

我的问题是这个。我想通过引用已经创建的基类实例来创建派生类的实例,所以当我通过派生实例更改基类的任何成员变量时,我可以通过上面演示的方式看到先前创建的基本实例的更改。

注意:我希望你能理解我的意思,因为我知道我的术语可能很少。请,不要苛刻。 :)

注意:我不会显示/编写构造函数,因为我不确定执行此操作的最佳方法是什么,即使存在且语法可能不正确。

2 个答案:

答案 0 :(得分:1)

这似乎表明了问题:

Base* base = new Base("Base Class");
Derived* derived = new Derived(base, 453.21);

因为通常没有必要分别构造Base类。您的派生类将隐式包含Base实例,您不必手动添加指针,也不必从ctor设置它。我不知道你的ctor看起来如何,但它应该看起来像这样:

Derived(const std::string& name, double p) : Base(name), price( p ) {}

如果这足以自行修复,那么好,否则发布 所有 示例代码。而不是我上面引用的代码中的两行,它应该看起来更像:

Derived* derived = new Derived("Base Class", 453.21);

如果您发布Derived的代码,对我们来说应该是显而易见的,并且在您的具​​体示例中向您解释它会更容易。

答案 1 :(得分:1)

你试图做的方式很奇怪,但你可以简单地使用像这段代码的继承概念:

class Base
{
public:
    Base(const string &name) : name(name) {}
    virtual void setName(const string &name) { this->name = name; }
    virtual string getName() const { return name; }
protected:
    string name;
};

class Derived : public Base
{
public:
    Derived(const string &name, double price) : Base(name), price(price) {}
private:
    double price;
};

int main()
{
    Derived* derived = new Derived("Base Class", 453.21);

    derived->setName("Name changed!");

    Base *base = derived;

    cout << "Name of instance: " << base->getName() << endl;
}

输出

  

实例名称:名称已更改!

您不需要创建Base对象并将其传递给派生对象。

相反,创建一个派生对象并将其地址传递给Base指针。