简体   繁体   English

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

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

I am trying to access a protected function in class Test but I have no idea how to do it. 我正在尝试访问Test类中的受保护函数,但我不知道该怎么做。

Ok I admit one fact that I'm asking this because there's one part of my homework which I am tasked to put a function as protected: and access it instead of putting it to public: 好的,我承认一个事实是我问这个问题,因为我的作业中有一部分任务是将功能设置为保护状态:并访问它而不是将其公开:

and I am not sure how should I do it. 而且我不确定该怎么做。

the code below is how I normally access a function but of course, it doesn't work since it's protected: 下面的代码是我通常访问函数的方式,但是,由于受保护,所以它不起作用:

Test.h 测试

#ifndef Test_Test_h
#define Test_Test_h

class Test {

protected:
      void sampleOutputMethod();
};

#endif

Test.cpp TEST.CPP

 #include "Test.h"

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

main.cpp main.cpp

 #include Test.h
 #include<iostream>

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

A protected function is just as good as private function if you try to access it from a class that is not part of your hierarchy. 如果尝试从不属于层次结构的类访问受保护的函数,则它与私有函数一样好。 You either have to make the class trying to access it a subclass of Test, or you have to declare it as friend class. 您要么必须使该类试图访问它作为Test的子类,要么必须将其声明为好友类。 I bet you need the first option. 我敢打赌,您需要第一个选择。

You can delegate the function as well. 您也可以委派该函数。 Create a public function that calls the protected one. 创建一个公共函数来调用受保护的函数。

This can be accomplished through either deriving Test or creating another class, Test2, and declaring Test a friend of Test2 and having Test2 contain an instance of Test. 这可以通过派生Test或创建另一个类Test2,然后将Test声明为Test2的朋友并让Test2包含Test的实例来实现。

Seeing all the instructions of your homework would help. 查看作业的所有说明将有所帮助。

There are essentially two ways of accessing a protected member: 1) Create a class that inherits from your class Test: 本质上,有两种访问受保护成员的方法:1)创建一个从您的类Test继承的类:

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

2) Create another class, and modify class Test to make the other class a friend of your Test class: 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