尝试从方法

时间:2016-06-06 11:06:21

标签: c++ linux pointers segmentation-fault g++

当我试图从classA的方法返回classB的对象时,g ++抛出'分段错误'。我不知道如何解决这个错误,如果有人能告诉我为什么会发生这个错误,我将不胜感激。 所以......这是代码:

  

classA.h

#include "classB.h"
#ifndef _CLASS_A_H_
#define _CLASS_A_H_
class ClassA{
private:
    int id;
    ClassB *ptr_classB;
public:
    ClassA();
    ClassA(int id, std::string name);

    inline void setID(int id){this->id = id;}

    inline int getID(){return this->id;}

    inline ClassB getClassB(){return this->ptr_classB;}

};

#endif
  

classA.cpp

#include "classA.h"
#include "classB.h"

ClassA::ClassA(){
    this->id = 0;
    ptr_classB = new ClassB();
}
  

classB.h

#ifndef _CLASS_B_H
#define _CLASS_B_H

class ClassB{
private:
    std::string name;
public:
    ClassB();
    inline std::string getName(){return this->name;}
};
#endif
  

classB.cpp

#include <string>
#include "classB.h"

ClassB::ClassB(){
    this->name = "default";
}
  

的main.cpp

#include <iostream>
#include "classA.h"

using namespace std;

int main(){
    ClassA *ptr_classA = new ClassA();

    cout << ptr_classA->getClassB().getName()  << endl;
    //asd

    return 0;
}
  

生成文件

SRC = src

INC = include

OBJ = obj

BIN = bin

LIB = lib

CXX = g ++

CPPFLAGS = -c -I $(INC)/ -std = c ++ 11

全部:$(BIN)/ main

$(BIN)/ main:$(OBJ)/main.o

$(CXX) -o $(BIN)/main $(OBJ)/main.o -Llib/ -lclasses

$(OBJ)/main.o: $(SRC)/main.cpp

$(CXX) $(CPPFLAGS) $(SRC)/main.cpp -o $(OBJ)/main.o

$(OBJ)/classA.o:$(SRC)/classA.cpp $(INC)/classA.h $(INC)/classB.h

$(CXX) $(CPPFLAGS) $(SRC)/classA.cpp -o $(OBJ)/classA.o

$(OBJ)/classB.o: $(SRC)/classB.cpp $(INC)/classB.h

$(CXX) $(CPPFLAGS) $(SRC)/classB.cpp -o $(OBJ)/classB.o

$(LIB)/libclasses.a:$(OBJ)/classA.o

ar rsv $(LIB)/libclasses.a $(OBJ)/classA.o 

1 个答案:

答案 0 :(得分:1)

清理代码:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="cntr" style="margin-left: 25px;">  
  
<img src="images/pen/red.png" id="red" class="stretch pen red" alt="" /> 
   
<img src="images/pen/orange.png" id="orange" class="stretch pen orange" alt="" />    

<img src="images/pen/yellow.png" id="yellow" class="stretch pen yellow" alt="" />    

<img src="images/pen/green.png" id="green" class="stretch pen green" alt="" />    

<img src="images/pen/blue.png" id="blue" class="stretch pen blue" alt="" /> 
   
<img src="images/pen/purple.png" id="purple" class="stretch pen purple" alt="" />    

<img src="images/pen/black.png" id="black" class="stretch pen black" alt="" />    

<img src="images/back.png" class="stretch undo " onClick="undoDraw();" alt="" style="padding-left: 10px;"/>

</div>

在COMPIL时间纠正错误后编译并执行正常,这让我想知道:你怎么设法编译这个以获得段错误?