简体   繁体   English

如何覆盖在C ++函数内部的另一个类中的一个类中定义的虚拟方法

[英]How to overwrite a virtual method defined in a class in another class which is inside a function in C++

I have a class A which is in a separate file( sayfile1.cpp ) 我有一个class A在单独的文件中( sayfile1.cpp

class A{
public:
      virtual int add(){
      int a=5;
      int b=4;
      int c = a+b;
      return c;
      }
};

Now in a different file(say file2.cpp ), i have a function(i have a many other things in this function) inside which i want to create a class inherited from class A and implement the virtual method declared in class A . 现在在另一个文件(例如file2.cpp )中,我有一个函数(该函数中有很多其他东西),我想在其中创建一个从class A继承的class A并实现在class A声明的虚拟方法。

void function(Mat param1, Mat param2)
{
  //Some process here..
  ..
  ..
  int c=100;
  class B:public A{
  public:
        virtual int add(){

        return c;
        }
  };

}

Now if i were to call the function int add() , i want the result of c to be 100 and not 9. 现在,如果我要调用int add()函数,我希望c的结果为100而不是9。

Is it possible to do something like this in C++ ?? 有可能在C ++中做类似的事情吗?

Thanks in advance 提前致谢

Define member variable: 定义成员变量:

class B: public A {
    int c_;
public:
    explicit B(int c):c_(c){};
    virtual int add() {
        return c_;
    }
}
B variable((100));

You need to split your file1.cpp into file1.h : 您需要将file1.cpp拆分为file1.h

#ifndef FILE1_H
class A {
public:
  virtual int add();
};
#endif

and file1.cpp with it's implementation: file1.cpp及其实现:

int A::add { /*your code * }

In the other file you include only the header file: 在另一个文件中,仅包含头文件:

#include "file1.h"

The following is not legal in C++: 以下是在C ++中不合法的内容:

void function(Mat param1, Mat param2)
{
  //Some process here..
  ..
  ..
  int c=100;
  class B:public A {
  public:
    virtual int add(){

    return c;
    }
 };

} }

Instead, you need something like this: 相反,您需要这样的东西:

class B : public A {
public:
    B(int v) : c(v) {}
    virtual int add(){ return c; }
private:
    int c;
};

void function(Mat param1, Mat param2)
{
  //Some process here..
  ..
  ..
  int c=100;
  B o(c);

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM