variable return type in c++ class

前端 未结 7 1737
花落未央
花落未央 2021-01-25 08:33

i have a class with the following structure:

class myClass
{
    private:
        int type;
        classOne objectOne;
        classTwo objectTwo;
    public:
          


        
7条回答
  •  情话喂你
    2021-01-25 08:54

    Unless the two types are related (in which case you can create a function that will return a pointer/reference to the common ancestor) you cannot do that directly in C++.

    C++ is a statically typed language, meaning that the type of every expression must be known at compile time, but you are trying to define a function whose return type depends on runtime values.

    Depending on the particular problem to solve, there might be different approaches that you could take, including using type erasure (return a boost::any, boost::variant or your own type-erasure).

提交回复
热议问题