C++:如何通过公共方法调用私有方法
C++ : How do I call private methods through public ones?
对于我们的项目,我们得到了一个代码片段,我们不应该以任何方式编辑。我们只允许在所述代码段中为原型编写函数定义。
我的问题和问题是关于以这种方式编写代码时我应该如何调用私有函数:
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
}
类定义声明成员函数methodOne
和methodTwo
,但不定义它们。您需要在类外定义它们。
// 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();
}
相关文章:
- 如何强制从重写方法调用重写的方法基方法?
- C++:使用方法调用析构函数的顺序是什么?
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 使用 object 中的方法调用带有 std::bind 和 std::function.target 的 C 样式函数
- 指向类方法调用的指针
- 如何使用 SFINAE 在方法调用中有条件地定义变量?
- 是否有可以处理方法调用依赖关系的设计模式?
- 如何缩短C++中的方法调用?
- 从部分专用模板方法调用模板非静态方法
- 有没有办法禁止派生类中的基类方法调用?
- 为什么这C++只在编译器上编码一个不明确的方法调用Microsoft?
- 从父方法调用子方法
- 如何将子方法调用到父方法
- 虚拟函数在哪里使用 vpointer to vtable 来解析方法调用,非虚拟方法存储在哪里以及如何解析它们?
- 从静态方法调用静态函数指针
- 从同一类中的另一个方法调用方法时出错
- 方法调用意外地像 l 值一样起作用
- 无法从派生的一个方法调用基类方法
- 从类方法调用命名空间中名为 Same 的函数时,重载解析失败
- C 多线程JAVA JNI方法调用