使用 ->GetString( " ") 时出现 Seg 错误,它位于单独的类中

Seg Fault when using ->GetString(" ") which is in a separate class

本文关键字:错误 Seg 于单独 gt GetString 使用      更新时间:2023-10-16

我现在正在练习一些基本的C ,并决定在标头文件中创建类,构造函数,getString等在单独的文件中函数。

当我使用对象创建对象时"人鲍勃"并使用"。该代码正常工作,但是如果我做一个人*鲍勃,setName(x(函数seg故障,当我使用 -> setName时(x,x为" abc"字符串或字符串变量

main.cpp


#include <iostream>
#include <string>
#include "namevalue.h"
using namespace std;

int main(){
   Person Bob;
   string temp = "bob";
   Bob.SetName(temp);
   Bob.SetMoney(3000);
   cout << Bob.GetName() << " " << Bob.GetMoney() << endl;
   return 0;
}

person.h

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
class Person{
public:
    Person();
    Person(int money, string name);
    void SetName(string y);
    void SetMoney(int x);
    int GetMoney();
    string GetName();

private:
    int money;
    string name;
};

person.cpp

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <array>
#include "namevalue.h"
using namespace std;
Person::Person(){
    name = " ";
    money = 0;
}

Person::Person(int x, string y){
    SetName(y);
    SetMoney(x);
}

void Person::SetMoney(int x){
    money = x;
}
void Person::SetName(string x){
    name = x;
}

int Person::GetMoney(){
    return money;
}

string Person::GetName(){
    return name;
}

如果声明指针变量,则需要先用有效的实例填充它。否则,它指向无效的内存,您将获得您正在遇到的内存故障。

这应该有效。

Person* Bob = new Person();
Bob->SetName("Bob");
Bob->SetMoney(3000);

完成后,释放内存。

delete Bob;