Pass abstract parameter to method, why not?

六月ゝ 毕业季﹏ 提交于 2019-12-10 18:10:03

问题


I've written an abstract class (with pure virtual functions), and I'd like to have a method accept one such class as a parameter. Given that the class is abstract, I understand that I couldn't pass an abstract class to any method, but why can't I pass a subclass of an abstract class to that method? How do I specify that a parameter should be any of the subclasses of a specified baseclass? This is all in C++.


回答1:


You need to specify the parameter as a pointer (or reference), e.g. Abstract * rather than Abstract. If Derived inherits from Abstract, you can pass a variable of type Derived * when Abstract * is expected, but you can't in general pass one of type Derived when Abstract is expected.




回答2:


Then you use polymorphism in C++.

Given any base class:

struct Base{};

and its subclasses:

struct SubClassA : public Base(){};
struct SubClassB : public Base(){};

If you declare:

void MyFunctionReference(Base&){};
void MyFunctionPointer(Base*){};

You can then call:

{
   SubClassA a;
   SubClassB b;

   MyFunctionReference(a); // by reference
   MyFunctionPointer(&b); // by pointer address
}



回答3:


You can indeed do this, observe:

Pure abstract class:

class Abstract {
public:
    virtual void foo() = 0;
};

Child of overrides member function:

class AbstractImpl : public Abstract {
public:
    void foo() override { std::cout << "Hi from subclass\n"; }
};

Now we declare a method that takes a reference type of the abstract class

void somefunc(Abstract &ab) {
    ab.foo();
}

Finally in main we instantiate the child class parameter

int main() {
    AbstractImpl test;
    somefunc(test); // prints Hi from subclass
    return 0;
}

Source: https://stackoverflow.com/a/11422101/2089675



来源:https://stackoverflow.com/questions/20434948/pass-abstract-parameter-to-method-why-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!