【问题标题】:Does a virtual function has to be void?虚函数必须是无效的吗?
【发布时间】:2021-10-05 16:41:09
【问题描述】:

我想知道用于多态性的虚函数是否可以返回类似 int 的东西,而不是返回 void。例如,getter 可以是虚拟的吗?

例子:

class Person{
int number;
public:
...
  virtual int get_number(){return number}
};

【问题讨论】:

  • 是的,虚函数可以返回值。
  • 出于兴趣,您为什么认为它需要作废?
  • 您忘记了return number 后面的分号 (;)。
  • 你敢用这种大胆的尝试来对抗你的编译器吗?您是否愿意与全神贯注的听众分享错误信息(如果有)?作为一般规则,我们在这里欣赏以下内容:(1)一个明显的问题。查看。 (2) 源代码。查看。 (3) 来自编译器和链接器的任何和所有输出,以及,如果程序编译和链接,它的输出。 丢失。在发帖之前,我们也对自己的研究感到高兴,尽管我们往往不了解这样做的人。

标签: c++ class polymorphism


【解决方案1】:

是的。这是一个代码示例,我们使用了虚函数getType()Source

#include <iostream>
#include <string>
using namespace std;

class Animal {
   private:
    string type;

   public:
    // constructor to initialize type
    Animal() : type("Animal") {}

    // declare virtual function
    virtual string getType() {
        return type;
    }
};

class Dog : public Animal {
   private:
    string type;

   public:
    // constructor to initialize type
    Dog() : type("Dog") {}

    string getType() override {
        return type;
    }
};

class Cat : public Animal {
   private:
    string type;

   public:
    // constructor to initialize type
    Cat() : type("Cat") {}

    string getType() override {
        return type;
    }
};

void print(Animal* ani) {
    cout << "Animal: " << ani->getType() << endl;
}

int main() {
    Animal* animal1 = new Animal();
    Animal* dog1 = new Dog();
    Animal* cat1 = new Cat();

    print(animal1);
    print(dog1);
    print(cat1);

    return 0;
}

【讨论】:

  • 你的例子有点奇怪,因为这里不需要虚函数。
【解决方案2】:

是的,用于多态的虚函数可以返回任何类型,而不是 void。 参考下面的代码。

#include<iostream>
#include<conio.h>
using namespace std;

class Person {
    int age1 = 24;
public:
    virtual int get_number() 
    { 
        return age1;
    }
};

class Developer : Person
{
    int age2 = 35;
public:
    int get_number()
    {
        return age2;
    }
};

void main()
{
    Person *p = new Person();
    Developer *p2 = new Developer();

    cout << p->get_number() << endl;
    cout << p2->get_number() << endl;

    _getch();
}

输出: 24 35

【讨论】:

    猜你喜欢
    • 2013-11-17
    • 2013-03-09
    • 2020-03-08
    • 1970-01-01
    • 2011-07-14
    • 2015-12-31
    • 1970-01-01
    • 2012-04-25
    • 2016-04-25
    相关资源
    最近更新 更多