我需要启动父类还是仅启动子类
Do I need to initiate parent class or just child class
我是编程新手,正在用父类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
我怀疑您正在查看的代码是为了演示如何将指向基类的指针与派生类的对象一起使用而编写的。不,指针对于这个学习练习的功能来说是不必要的。事实上,这可能就是选择此功能的原因。既然你看到了如何在没有指针的情况下完成同样的事情,那么你应该更容易将指针与你已经知道的内容联系起来。
我在这个练习中看到的关键学习点是
- 相同的指针类型(
fruit *
)可以指向不同类型的对象(apple
或pear
) - 使用指向基类的指针时,可以访问基类成员
- 使用指向基类的指针时,不能访问派生类成员。(由省略暗示;将使用
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函数仍然可以对数组中的元素执行操作,而不需要知道它们在继承树中属于哪个对象类型(由于虚拟函数)。这对于利用多态性以及节省函数和代码的重复是至关重要的。
相关文章:
- 继承期间显示未知行为的子类
- 通过指向指针数组的指针访问子类的属性
- 从父类方法返回子类对象
- c++, 在子类中,如何在没有对象的情况下访问父类的方法?
- 将父类对象强制转换为子类的问题
- 避免在C++中重复子类定义
- 将QOpenGLWidget子类转换为使用Metal而不是OpenGL的子类是否可行?
- 如何初始化矢量的模板化子类
- C++ 继承:将子类传递给需要基类的函数并获取子类行为
- 有没有办法按值将纯抽象类的所有子类传递给 C++ 中的函数?
- 使用子类覆盖基类中定义的函数
- 子类地址等于虚拟基类地址?
- 将子类方法声明为基类的友元
- C++子类共享变量?
- 如何检查模板专用化是否是基本模板的子类?
- 仅让特定类'Fabric'构造类'Foo'及其所有子类的实例
- 使用模板参数重载C++方法:如何使其适用于模板的子类?
- 基类中的默认析构函数禁用子类中的移动构造函数(如果有成员)
- 我需要启动父类还是仅启动子类
- 父类析构函数删除具有外部启动元素的子类