C++:如何通过公共方法调用私有方法

C++ : How do I call private methods through public ones?

本文关键字:方法 调用 有方法 何通过 C++      更新时间:2023-10-16

对于我们的项目,我们得到了一个代码片段,我们不应该以任何方式编辑。我们只允许在所述代码段中为原型编写函数定义。

我的问题和问题是关于以这种方式编写代码时我应该如何调用私有函数:

class ClassOne {
    private:
    void methodOne();
    public:
    void methodTwo();
};

所以我应该能够通过方法二访问方法一,但不在方法一旁边写{ methodTwo();}。请帮帮我?

你已经有了你的class

class ClassOne {
    private:
    void methodOne();
    public:
    void methodTwo();
};

实现class functions

void ClassOne::methodOne() { // <-- private
   // other code
}
void ClassOne::methodTwo() { // <-- public
   // other code
   methodOne();              // <-- private function called here
}

类定义声明成员函数methodOnemethodTwo,但不定义它们。您需要在类外定义它们。

// I assume the return type is void since you omitted it, but
// keep in mind the compiler will not allow you to omit it!
void ClassOne::methodOne() {
    // ...
}
void ClassOne::methodTwo() {
    // ...
    methodOne(); // OK since access is from a member of ClassOne
    // ...
}

私有函数仅对对象外部的事物私有。您可以像任何其他函数一样正常调用 m2 中的 m1。

要从methodTwo调用methodOne,只需将method2定义为:

void ClassOne::methodTwo() {
    methodOne();
}

所有私有函数和变量都可以从公共函数访问。 因此,您可以按如下方式调用私有函数:

void ClassOne::methodTwo(){
   methodOne();
}