![](/img/trans.png)
[英]How to assign a pointer to base class to an object of a derived class in c++?
[英]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.