从另一个类 C++ 访问受保护的函数

accessing protected function from another class c++

本文关键字:受保护 函数 访问 C++ 另一个      更新时间:2023-10-16

我正在尝试访问类测试中的受保护函数,但我不知道该怎么做。

好的,我

承认我问这个的一个事实是,因为我的家庭作业中有一部分我的任务是将一个功能作为受保护的:并访问它而不是将其公开:

我不确定我应该怎么做。

下面的代码是我通常访问函数的方式,但当然,它不起作用,因为它受到保护:

测试.h

#ifndef Test_Test_h
#define Test_Test_h
class Test {
protected:
      void sampleOutputMethod();
};
#endif

测试.cpp

 #include "Test.h"
 void Test::sampleOutputMethod()  {
    std::cout << "this is a test output method" << std::endl;
 }

主.cpp

 #include Test.h
 #include<iostream>
 int main() {
    Test test;
    test.sampleOutputMethod();
 }

基本上有两种访问受保护成员的方法:1) 创建一个继承自类 Test 的类:

class Test2 : public Test {
public:
    void sampleOutputMethod() { ::sampleOutputMethod; }
}

2)创建另一个类,并修改类Test以使另一个类成为你的测试类的朋友:

class Test;  // Forward declaration of Test
class Test2 {
public:
    void output( Test& foo ) { foo.sampleOutputMethod(); }
}
class Test {
protected:
    void sampleOutputMethod();
}

如果您尝试从不属于层次结构的类访问受保护的函数,则受保护的函数与私有函数一样好。您要么必须使尝试访问它的类成为 Test 的子类,要么必须将其声明为友元类。我敢打赌你需要第一个选项。

您也可以委派函数。创建一个调用受保护函数的公共函数。

这可以通过派生 Test 或创建另一个类 Test2 来实现,并将 Test 声明为 Test2 的

好友并让 Test2 包含 Test 的实例。

查看家庭作业的所有说明会有所帮助。

如果允许修改类 Test,可以添加一个调用 "sampleOutputMethod" 的公共函数,也可以使用此技巧返回 "sampleOutputMethod" 的函数指针 https://stackoverflow.com/a/6538304/1784418