variable return type in c++ class

前端 未结 7 1723
花落未央
花落未央 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:42

    I am not sure why you would not use templates for your case.

    You can have something like below:

    template 
    class myClass
    {
        private:
            int type;
            ClassType object;            
        public:
            myClass(ClassType object_in)
            {
                this->object = object_in;
                /*
                    C++ doesn't support reflection so I don't think there 
                    is a robust way of doing the following at runtime.
                */
                type = /* Get Type at runtime */;
            }
            /*
                Have another method which return object in a straigtforward way.
            */
    };
    

    However, then this become trivial. Any more insight into what your use case is, such that you have to know the type?

    Update: If the ClassType is going to be an Object, you can have a const static int TypeID member for the class, which is set at compile time. You can then use it determine the Type at runtime.

提交回复
热议问题