簡體   English   中英

C++ Unable to assign base class “this” pointer the derived class object inside base class constructor

[英]C++ Unable to assign base class “this” pointer the derived class object inside base class constructor

嗨,我正在學習 C++ 並試圖構建一些基礎 class *此指針被分配派生的 class ZA8CFDE63311BD59EB2AC96B6 使用以下構造的東西我的問題是,在 C++ 中是否有可能以這種方式? 因為,當我嘗試編譯它時,我得到了錯誤


錯誤:“Derived_1”之前的預期類型說明符


如果這樣的事情是可能的,那么正確的方法是什么。 我這樣做的目的是通過基本 class 自動獲取相對派生的 class 實現,基於 DISPLAY 類型,以避免主要的 if-else 類子句。 任何幫助都感激不盡。

#ifndef _MAIN_HPP_
#define _MAIN_HPP_

#include <iostream>

enum class DISPLAY {
    DERIVED_1 = 1,
    DERIVED_2 = 2
};

class Base {
    private:
        int variable = 0;
    public:
        Base(){std::cout<<"Base Class Empty Constructor"<<std::endl;}
        Base(DISPLAY Type) {
            std::cout<<"Base Class Constructor Derived_"<<static_cast<int>(Type)<<std::endl;
            switch(Type) 
            {
                case(DISPLAY::DERIVED_1): {
                    *this = new Derived_1();
                }break;
                case(DISPLAY::DERIVED_2): {
                    *this = new Derived_2();
                }break;
            }
        }
        virtual ~Base() {std::cout<<"This is Base Class Destructor"<<std::endl;}
        virtual int Sum(int x, int y) {return x+y;};
};

class Derived_1 : public Base {
    public:
        Derived_1(){std::cout<<"This is Derived_1 Class Constructor"<<std::endl;}
        virtual ~Derived_1() {std::cout<<"This is Derived_1 Class Destructor"<<std::endl;}
        int Sum(int x, int y) {return (x*2)+(y*3);}
};

class Derived_2 : public Base {
    public:
        Derived_2(){std::cout<<"This is Derived_2 Class Constructor"<<std::endl;}
        virtual ~Derived_2() {std::cout<<"This is Derived_2 Class Destructor"<<std::endl;}
        int Sum(int x, int y) {return (x*1)+(y*2);}
};
#endif

#include "main.hpp"

using namespace std;

int main(int argc, char **argv)
{
    Base *base = new Base(DISPLAY::DERIVED_1);
    cout<<"SUM:"<<base->Sum(2, 10)<<endl;
    return 0;
}

錯誤摘要:

/home/junaid/workspace/Learn_Cpp/main.hpp: In constructor ‘Base::Base(DISPLAY)’:
/home/junaid/workspace/Learn_Cpp/main.hpp:21:33: error: expected type-specifier before ‘Derived_1’
   21 |                     *this = new Derived_1();
      |                                 ^~~~~~~~~
/home/junaid/workspace/Learn_Cpp/main.hpp:24:33: error: expected type-specifier before ‘Derived_2’
   24 |                     *this = new Derived_2();
      |                                 ^~~~~~~~~

Build finished with error(s).
The terminal process terminated with exit code: -1.

你絕對不能做你正在做的事情。 你不能這樣做:

                *this = new Derived_1();

我什至不想考慮這一切有什么問題。 你想要的是實現工廠模式(你可以用谷歌搜索)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM