【发布时间】:2019-02-08 12:44:51
【问题描述】:
我是编程新手,我正在使用父类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*作为参数传递给函数)。 -
不,您不需要刚刚发布的代码中的指针。我想问题是为什么你认为指针可能是必要的。您可能正在尝试了解多态性,但您发布的代码不使用多态性,因此不需要指针。
-
也许作为练习写一个
eat_some_fruit(fruit&);函数,你可以传递任何水果,这可能会更清楚 -
此代码无法为我编译。除了未翻译的函数名称之外,
apple apple;也会编译,但这是一个真的坏主意。
标签: c++ pointers inheritance