我需要上家长课还是只上孩子课?

时间:2019-02-08 12:44:51

标签: c++ pointers inheritance

我是编程新手,我正在使用父类水果和子类苹果和梨来分析代码。在此示例中,有指向父类的指针。扩展此代码后,我发现使用对象可以访问父公共成员和所有子成员。问题是为什么我需要那些指针?

// are this pointer needed since I can use j.setWeight(11)

#include <iostream>

using namespace std;

class fruit {
private:
    int weight;

public:
    void setWeight(int x)
    {
        weight = x;
    }
    int getWeight()
    {
        return weight;
    }
};

class apple : public fruit {
public:
    void eat()
    {
        cout << "Now I am eating apple"
             << "=" << getWeight() << endl;
    }
};

class pear : public fruit {
public:
    void eat()
    {
        cout << "Now I am eating pear"
             << " = " << getWeight() << endl;
    }
};

int main()
{
    apple j;
    pear k;
    fruit* fruit1 = &j;
    fruit* fruit2 = &k;
    k.setWeight(5);
    k.eat();
    fruit1->setWeight(11);
    apple apple;
    apple.postaviTezinu(16);
    apple.jelo();

    return 0;
}

are this pointers needed since I can use j.setWeight(11) and results is same as 
fruit1 -> setWeight(11) ... what s difference, thx

2 个答案:

答案 0 :(得分:0)

由于您是编程的新手,所以在此阶段,学习多态性可能会有所提高。要直接回答您的问题:不,您无需在示例代码中使用指针,它们对您毫无帮助。

但是,指向对象的指针通常可用于:

  • 减少不必要的对象复制
  • 在多态的情况下(如您的示例),指针可在程序的某些部分提供帮助,在这些部分中您不知道要处理的对象类型,或者不想用不同的方式处理它们

示例:

#include <iostream>
#include <vector>

class A
{
public:
    virtual void foo ()
    {
        std::cout << " I am A\n";
    }
};

class B : public A
{
public:
    virtual void foo ()
    {
        std::cout << " I am B\n";
    }
};

void bar ( const std::vector <A*> & obj )
{
    // Here it outputs the foo () function that is
    // appropriate for the class
    for ( unsigned int i = 0; i < obj . size (); ++i )
        obj [i] -> foo ();
}

int main ()
{
    A a1, a2, a3;
    B b1, b2, b3;

    // the below input style requires C++11,
    // otherwise input them one-by-one
    std::vector <A*> array {&a1, &b1, &a2, &a3, &b2, &b3};

    bar ( array );

    return 0;
}

以上array可以存储任何A对象,包括继承的对象(没有指针就无法做到);并且bar函数仍然可以对数组中的元素执行操作,而无需知道它们在继承树中属于哪种对象类型(由于虚函数)。这对于充分利用多态性以及节省功能和代码的重复性至关重要。

答案 1 :(得分:0)

我怀疑您正在查看的代码是为演示如何将基类的指针与派生类的对象一起使用而编写的。不,此学习练习的功能不需要指针。实际上,这可能就是选择此功能的原因。由于您了解了如何在没有指针的情况下完成相同的事情,因此将指针与您已经知道的内容联系起来应该更容易。

我在本练习中看到的关键学习要点是

  1. 相同的指针类型(fruit *)可以指向不同类型的对象(applepear)。
  2. 使用指向基类的指针时,您可以访问基类成员。
  3. 使用指向基类的指针时,不能访问派生类成员。 (表示为省略;将kfruit1进行的操作进行比较。)

您将需要继续学习更高级的课程,以了解何时指针比直接访问对象更有用(可能在eat()变成虚拟函数之后)。现在,只需了解如何通过不同方式完成相同任务即可。

(当然,您可以在此处获得该信息,但是该代码看起来像是一个系列的一部分。继续学习该系列可能是学习的更好方法。)

相关问题