提问人:Sheikh Muhammad Junaid Aslam 提问时间:3/30/2021 最后编辑:Alan BirtlesSheikh Muhammad Junaid Aslam 更新时间:3/30/2021 访问量:114
C++ 无法为基类构造函数中的派生类对象分配基类“this”指针
C++ Unable to assign base class "this" pointer the derived class object inside base class constructor
问:
嗨,我正在学习 C++,并试图构造一些东西,其中基类 *此指针使用以下构造分配派生类对象。我的问题是,在 C++ 中可能以这种方式吗?因为,当我尝试编译它时,我得到错误
错误:在“Derived_1”之前应有类型说明符
如果这样的事情是可能的,那么正确的方法是什么。我这样做的目的是根据 DISPLAY Type 通过基类自动获取相对派生类实现,以避免 main 中的 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.
答:
0赞
Joseph Larson
3/30/2021
#1
你绝对不能做你正在做的事情。你不能这么做:
*this = new Derived_1();
我什至不想考虑所有错误的事情。相反,你想要的是实现工厂模式(你可以谷歌搜索)。
评论
Base
Base
Derived_1
Derived_2
_MAIN_HPP_