测试版530中的阵列大小调整问题 - 页 8

 
angevoyageur:
在水果(苹果、梨)、猫、狗和动物之后。人们在谈论op的时候,缺乏想象力是很可怕的。(cyclops993,不是说你,是说维基百科。)哪个真正的程序需要一个带有 "说话 "方法的 "动物 "类。我将尽快发布一个 "交易 "的例子。

稍微完整一点的例子脚本。

class Animal {
    public: virtual string talk() {return "";}
};
 
class Cat : public Animal {
    public: string talk() {return "Meow!";}
};
 

class Dog : public Animal {
    public: string talk() {return "Woof!";}
};

void OnStart()
{
   Animal * random;
   if (GetTickCount() % 2 == 0) {
      random = new Cat();
   } else {
      random = new Dog();
   }
   MessageBox(random.talk());  
   delete random;
}

我之前没有注意到的是,如果有对基类的引用,似乎就不可能有没有主体的虚函数。在上面的例子中,你不能做以下事情。

class Animal {
   public: virtual string talk();
};

...而在C++中,你可以 做以下事情。

class Animal {
    public: virtual const char * talk() = 0; // Pure virtual function
};
 
class Cat : public Animal {
    public: const char *  talk() {return "Meow!";}
};
 

class Dog : public Animal {
    public: const char * talk() {return "Woof!";}
};

void main()
{
   Animal * random;
   if (GetTickCount() % 2 == 0) {
      random = new Cat();
   } else {
      random = new Dog();
   }
   printf(random->talk());   
}
 
SDC:

那么,你怎么称呼猫类和狗类,它们是动物的子类吗? 你可以在狗类中创建另一个狗的子类,并称它为比特犬类?

是的,就是这样。当使用这些类时,你使用一个变量,并影响到一个类和它的子类的任何对象。如cyclops993的例子所示(主函数),当你调用talk()时,会使用好的函数。
 

好的,这很好,我想我要努力学习这个。

 
SDC:

好的,这很好,我想我要努力去学习这个。

比如说。

class Pitbull : public Dog {
   public: 
      string talk() {return "Growl!";}
      void menace() {}
};

...比特犬不仅能像猫和其他狗一样说话,而且还能威胁东西。