简体   繁体   English

访问受保护的成员函数! 分段故障(核心已转储)

[英]Accessing protected member function ! Segmentation fault (core dumped)

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 ++库用于项目,并且想要使用此库的类的受保护成员函数。 As can't access protected members directly outside class or derived class; 由于不能直接在类或派生类外部访问受保护的成员; to use protected method of Balloon Layout class I created a class A which inherit BallonLayout class and from A protected function of super class is called in a public function "abc()" of class A; 为了使用Balloon Layout类的受保护方法,我创建了一个继承BallonLayout类的类A,并从A类的受保护函数中调用了A类的公共函数“ abc()”; so that I can use abc() outside the class and indirectly protected function of class BallonLayout. 这样我就可以在类外部使用abc()并间接保护BallonLayout类的功能。

Here posting the code please tell me where is 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);                
            }
};

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

    A* 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 not getting what mistake have I done. 但是我没有犯什么错误。

Your code: 您的代码:

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

doesn't initialize the pointer a . 不会初始化指针a Dereferencing a null or uninitialized pointer, with either the * or -> operator, is undefined behavior . 使用*->运算符取消引用null或未初始化的指针是未定义的行为

Turns out, you don't need the pointer at all, just use: 原来,您根本不需要指针,只需使用:

A a;
a.abc(G);

And if you need dynamically allocated memory, include <memory> and do: 如果需要动态分配的内存,请包含<memory>并执行以下操作:

std::unique_ptr<A> a = new A(...);
a->abc(G);

For the love of life, the universe and everything, don't use naked pointers when you can. 为了热爱生命,宇宙和一切,请尽可能不要使用裸露的指针。

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

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