简体   繁体   English

在派生类中访问受保护的成员函数-分段错误

[英]Accessing protected member function in derived class — Segmentation fault

I am trying to use OGDF C++ library for a project and want to use a protected member function of a class of this library. 我正在尝试将OGDF C ++库用于项目,并且想要使用此库的类的受保护成员函数。 I can't access protected members directly outside class or derived class, so to use protected method of Balloon Layout class I created a class A which inherits from BallonLayout . 我不能直接在类或派生类外部访问受保护的成员,因此要使用Balloon Layout类的受保护方法,我创建了ABallonLayout继承的类A From A , a protected function of the super class is called in a public function abc() of class A ; A ,在类A的公共函数abc()中调用超类的受保护函数; so that I can use abc() outside the class and indirectly protected function of class BallonLayout . 这样我就可以在类外部使用abc()并间接保护BallonLayout类的BallonLayout

Here's the code, please tell me where there is a problem in it. 这是代码,请告诉我其中有问题。

#include <ogdf/basic/Graph.h>
#include <ogdf/basic/graph_generators.h>
#include <ogdf/misclayout/BalloonLayout.h>

using namespace ogdf;

class OGDF_EXPORT A : public BalloonLayout{
        public:
            void abc(const Graph &G){
            selectRoot(G); //Calling super class protected method.               
            }
};

int main()
{
    int n = 5, m = 7;
    Graph G;
    ogdf::planarBiconnectedGraph(G, n, m);

    A* a = new A;
    a->abc(G);
    cout << "Done!!";
return 0;

}

It compiles without any error but at run time it gives “Segmentation fault (core dumped)”. 它编译时没有任何错误,但在运行时给出“分段错误(内核已转储)”。 This error comes when we try to access something (object/variable) which is not in memory. 当我们尝试访问内存中没有的内容(对象/变量)时,会出现此错误。 But I do not understand what mistake have I done. 但是我不明白我犯了什么错误。

In place of A* a = new A; a->abc(G); 代替A* a = new A; a->abc(G); A* a = new A; a->abc(G); , I tried the following too but I am getting the same error. ,我也尝试了以下操作,但出现了同样的错误。

A* a; 
a->abc(G);

and

A *a = new A;
a->abc(G);
delete a;

and

A a;
a.abc(G);

Foe each one of the attempts above, I get a segmentation fault. 仇恨上面的每一次尝试,我都遇到了分段错误。 This error is coming after calling a.abc(G) when this method calls the superclass's method. 当此方法调用超类的方法时,在调用a.abc(G)之后会出现此错误。

A* a;
a->abc(G);

That creates a pointer without initialising it; 这将创建一个指针而不初始化它; then attempts to dereference that invalid pointer to call a function. 然后尝试取消引用该无效指针以调用函数。 The result is a segmentation fault, or other undefined behaviour. 结果是分段错误或其他未定义的行为。

You almost certainly want to create an object: 您几乎可以肯定要创建一个对象:

A a;
a.abc(G);

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

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