g++在我试图从classA的方法返回classB的对象时抛出"segmentation fault"。我不知道如何修复这个错误,如果有人能告诉我为什么会发生这个错误,我将不胜感激。所以…这是代码:
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;
}
Makefile
SRC=SRC
INC=包括
OBJ=目标
BIN=仓
LIB=LIB
CXX=g++
CPPFLAGS=-c-I$(INC)/-std=c++11
全部:$(BIN)/主
$(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)/calassA.o:$(SRC)/classA.cpp$(INC)/cclassA.h$(INC)/classB.h
$(CXX) $(CPPFLAGS) $(SRC)/classA.cpp -o $(OBJ)/classA.o
$(OBJ)/classB.o:$(SRC)/classB.cpp$(INC)/cclassB.h
$(CXX) $(CPPFLAGS) $(SRC)/classB.cpp -o $(OBJ)/classB.o
$(LIB)/libclasses.a:$(OBJ)/classA.o
ar rsv $(LIB)/libclasses.a $(OBJ)/classA.o
已清理代码:
class ClassA ;
class ClassB ;
class ClassB{
private:
int n;
public:
ClassB();
inline void set_n(int n){this->n =n;}
inline int get_n(){return this->n;}
};
class ClassA{
private:
ClassB *ptr_classb;
public:
ClassA();
inline ClassB getClassBObject(){return *ptr_classb;}
};
ClassB::ClassB(){
this->n = 0;
}
ClassA::ClassA(){
ptr_classb = new ClassB();
}
#include <iostream>
int main(){
ClassA *ptr_classA = new ClassA();
std::cout << ptr_classA->getClassBObject().get_n() << std::endl;
return 0;
}
在COMPIL时间更正错误后,编译和执行都很好,这让我想知道:你到底是怎么编译得到segfault的?