简体   繁体   中英

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

I'm practicing some basic C++ right now, and decided to create a class in a header file and the constructor, GetString, etc functions in a separate file.

When I create my object using "Person Bob" and use "." the code works fine, but if I do Person* Bob, the SetName(x) function seg faults, when I use ->SetName(x, with x being a "abc" string or a string variable

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;
}

If you declare a pointer variable, you need to populate it first with a valid instance. Otherwise, it is pointing to invalid memory and you will get the memory fault you are experiencing.

This should work.

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

When you're finished, free the memory.

delete Bob;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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