C++ 我需要启动父类还是子类
我是编程新手,我正在分析父类fruit和子类apple和pear的代码。在这个例子中,有一个指向父类的指针。在我扩展了这段代码之后,我发现使用object可以访问父公共成员和所有子成员。问题是为什么我需要这些指针C++ 我需要启动父类还是子类,c++,pointers,inheritance,C++,Pointers,Inheritance,我是编程新手,我正在分析父类fruit和子类apple和pear的代码。在这个例子中,有一个指向父类的指针。在我扩展了这段代码之后,我发现使用object可以访问父公共成员和所有子成员。问题是为什么我需要这些指针 // are this pointer needed since I can use j.setWeight(11) #include <iostream> using namespace std; class fruit { private: int wei
// 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
//因为我可以使用j.setWeight(11),所以需要这个指针吗
#包括
使用名称空间std;
等级水果{
私人:
整数权重;
公众:
无效设定重量(整数x)
{
重量=x;
}
int getWeight()
{
返回重量;
}
};
苹果类:公众水果{
公众:
空吃
{
cout由于您是编程新手,在这一阶段学习多态性可能会有点高级。直接回答您的问题:不,示例代码中不需要指针,它们也没有任何帮助
但是,指向对象的指针通常用于:
- 减少不必要的对象复制
- 在多态性的情况下(如您的示例中),指针在您的程序中不知道要处理哪种对象类型,或者不想以不同的方式处理它们的部分会有所帮助
例如:
#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;
}
#包括
#包括
甲级
{
公众:
虚拟void foo()
{
std::cout我怀疑您正在查看的代码是为了演示如何将指向基类的指针用于派生类的对象。不,指针不是此学习练习功能所必需的。事实上,这可能就是选择此功能的原因。因为您看到了如何实现相同的目的如果没有指针,将指针与您已经知道的内容联系起来应该会更容易
我在本练习中看到的关键学习点是
同一指针类型(fruit*
)可以指向不同类型的对象(apple
或pear
)
使用指向基类的指针时,可以访问基类成员
使用指向基类的指针时,无法访问派生类成员。(省略表示;将使用k
执行的操作与使用1
执行的操作进行比较)
当指针比直接访问对象更有用时(可能在eat()
变成虚拟函数之后),您需要继续学习更高级的课程。现在,只需学习如何通过不同的方式完成相同的任务
(当然,你可以在这里得到这些信息,但是代码看起来就像是系列的一部分。继续这个系列可能是更好的学习方法)
我认为你需要更仔细地研究多态性和虚拟函数。(如将水果*
作为参数传递给函数)不,你不需要刚刚发布的代码中的指针。我想问题是为什么你认为指针可能是必要的。你可能试图了解多态性,但你发布的代码没有使用多态性,因此不需要指针。也许作为练习,写一篇吃一些水果(水果&)
函数,您可以传递任何结果,这可能会更清楚这段代码没有为我编译。除了未翻译的函数名,apple;
将编译,但这是一个非常糟糕的主意。我学习了虚拟函数,现在我可以使用指针访问继承类的成员函数,如果我理解如果在继承的类中未定义此函数,则我可以正确地定义默认函数行为:)。