在C ++中不继承的情况下在另一个类中使用一个函数

时间:2020-06-27 17:28:18

标签: c++ oop

情况是这样的:

export const CategoriesProvider = props => {
  return (
    <CategoriesContext.Provider value={"Hello"}>
      {props.children}
    </CategoriesContext.Provider>
  );
};
//header file

#ifndef CLASSA_H
#define CLASSA_H

#include <stdint.h>

class ClassA
{
public:
    void function1();

    void function2();
};

#endif //CLASSA_H
//cpp file
#include "ClassA.h"
void ClassA::function1()
{
    /* some code */
}
void ClassA::function2()
{
    /* some more code */
}
void function3()
{
    /* more code /*
}

我想在main.cpp中调用function3()但没有继承。我尝试使用ClassA的实例,但是说“ function3不是classA的成员”。 也许我错过了一个概念,如果有人可以提供帮助,那就太好了。

2 个答案:

答案 0 :(得分:0)

当您尝试使用function3()语法调用obj.function3()时,编译器将尝试查找类实例(即对象)中是否存在名为function3的函数。 / p>

现在,在这种情况下,您可以做两件事:

  1. 在类的void function3()中包含public:并将void function3()更改为void ClassA :: function3(),以告知编译器为类成员函数定义了包含的代码

  2. 或者,在头文件中定义函数,并通过定义类对象防止调用该函数。很明显,因为您不能访问在类外部声明的内容。


以上两种方法的代码说明如下:

方法1

ClassA.cpp

#include "ClassA.h"
...
void ClassA::function3() // definition of the class member function
{
    /* more code */
}

main.cpp

#include "ClassA.h"
int main()
{
    ClassA obj;
    obj.function3(); // now it's inside the class member function
                     // hence, we may now use it
}

ClassA.h

...
class ClassA
{
public:
    ...
    void function3(); // declared inside the class
};

#endif //CLASSA_H

方法2

ClassA.h

...
void function3()
{
    /* more code */
}

main.cpp

#include "ClassA.h"
int main()
{
    function3();
}

ClassA.cpp

class {
    ...
};

void function3()
{
    /* more code */
}

但是第二种方法会使该类无用,因此,您可能打算实现第一种方法,而不是第二种。

答案 1 :(得分:-1)

function3()没有在类A中声明。 obj.fuction3()没什么意义。如果要对A类的对象进行操作,则可以在function3中进行更改,以便它可以从main接收该对象作为参数。 P.S该对象将通过引用发送。

相关问题