我需要启动父类还是仅启动子类

Do I need to initiate parent class or just child class

本文关键字:启动 子类 父类      更新时间:2023-10-16

我是编程新手,正在用父类fruit和子类apple和pear分析代码。在这个例子中,有一个指向父类的指针。在我扩展了这段代码之后,我发现使用对象我可以访问父公共成员和所有子成员。问题是我为什么需要这些指针?

// 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

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

我在这个练习中看到的关键学习点是

  1. 相同的指针类型(fruit *)可以指向不同类型的对象(applepear)
  2. 使用指向基类的指针时,可以访问基类成员
  3. 使用指向基类的指针时,不能访问派生类成员。(由省略暗示;将使用k所做的与使用fruit1所做的进行比较。)

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

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

由于您是编程新手,在这个阶段学习多态性可能会有点高级。直接回答你的问题:不,你的示例代码中不需要指针,它们也毫无帮助。

然而,指向对象的指针通常用于:

  • 减少不必要的对象复制
  • 在多态性的情况下(如您的示例),指针在程序中不知道要处理哪种对象类型,或者不想以不同的方式处理它们的部分会有所帮助

示例:

#include <iostream>
#include <vector>
class A
{
public:
virtual void foo ()
{
std::cout << " I am An";
}
};
class B : public A
{
public:
virtual void foo ()
{
std::cout << " I am Bn";
}
};
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对象,包括继承的对象(没有指针就无法做到这一点);并且CCD_ 8函数仍然可以对数组中的元素执行操作,而不需要知道它们在继承树中属于哪个对象类型(由于虚拟函数)。这对于利用多态性以及节省函数和代码的重复是至关重要的。