一个对象有多个类

一个对象有多个类

本文介绍了一个对象有多个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我声明一个通用对象.对象类型与用户输入有关.根据用户输入,该对象将被声明为现有类之一.声明对象的正确方法是什么?
我现在使用它的方式如下:
在driver.cpp中,我这样声明对象:

I declare a generic object. the object type has to do with user input. based on the user input, the object will be declared to one of the existing classes. What is the proper way of declaring the object?
The way I use it now is as follows:
in driver.cpp, I declare the object like this:

BEPOCH cEpoch(diff);


我使用它的方式如下:


I use it as follows:

cEpoch.p->getinput();
 cEpoch.p->process();

...
在具有不同功能的所有类中定义了getinput()和process()的地方.
在driver.h中,我声明BEOPCH类如下:

...
where getinput() and process() are defined in all classes with different functionality.
In driver.h, I declare the BEOPCH class as follows:

class BEOPCH
{
  void* p;
  BEPOCH(int diff){
      if(diff == 0) p = (CEPOCH*) malloc(sizeof(CEPOCH));
      else if(diff == 1) p = (DEPOCH*) malloc(sizeof(DEPOCH));
}


在每个特定的类定义中,我使void指针指向类本身:


In each specific class definition, I make the void pointer point to the class itself:

CEPOCH(void* p){p = this;}


我收到以下编译错误:


I get the following compilation error:

[BCC32 Error] driver.cpp(576): E2288 Pointer to structure required on left side of -> or ->*



我做错什么了?正确的做法是什么?
谢谢.



What did I do wrong? What is the right way of doing that?
Thanks.

推荐答案


class MyClass {
public:
   void MyMethod() {
      //...
      this->someField = //... this is a pointer to instance passed as a parameter (implicit)
      //...
   }
   //...
private: //what I explain has nothing to do with access modifiers; this is just to make the example clear
   int someField;
   //...
} //my Class

//...

MyClass myInstance();
myInstance.MyMethod(); //&myInstance (a pointer made of myInstance by getting its address) is passed to MyClass::MyMethod to give you access to the instance

MyClass * myOtherInstance() = new MyClass();
myOtherInstance->MyMethod(); //myInstance (already a pointer) is passed to MyClass::MyMethod
//...
delete myOtherInstance;



在两种情况下,实例指针&myInstancemyOtherInstance都传递到"."或"->"右侧所示的方法,并成为this指针.在大多数情况下,除非需要解决一些名称冲突,否则关键字"this"本身可以省略.我已经展示了这种"this"语法,只是为了使事情的本质更加清晰.

我建议您从一开始就开始学习C ++或所有C ++的面向对象部分.现在,您正在转向错误的方式.不用担心,只要确定方向即可.

—SA



In both cases of instance pointers &myInstance and myOtherInstance are passed to method shown on right of "." or "->" and become this pointer. The keyword "this" itself could be omitted in most cases, unless you need to resolve some name conflict; I''ve shown this "this" syntax just to make the essence of things more clear.

I suggest you start learning object-oriented part of C++ or maybe all of C++ from the very beginning. Right now you''re turning to the wrong way. Not to worry, just fix your direction.

—SA



这篇关于一个对象有多个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:20