繁体   English   中英

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

[英]accessing protected function from another class c++

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

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

而且我不确定该怎么做。

下面的代码是我通常访问函数的方式,但是,由于受保护,所以它不起作用:

测试

#ifndef Test_Test_h
#define Test_Test_h

class Test {

protected:
      void sampleOutputMethod();
};

#endif

TEST.CPP

 #include "Test.h"

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

main.cpp

 #include Test.h
 #include<iostream>

 int main() {
    Test test;
    test.sampleOutputMethod();
 }

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

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

这可以通过派生Test或创建另一个类Test2,然后将Test声明为Test2的朋友并让Test2包含Test的实例来实现。

查看作业的所有说明将有所帮助。

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

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

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

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

class Test {
protected:
    void sampleOutputMethod();
}

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

暂无
暂无

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

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