使用-> GetString(“”)(在单独的类中)时出现段错误

时间:2019-08-06 00:51:11

标签: c++

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

当我使用创建对象时 “人鲍勃”,然后使用“。”代码可以正常工作,但是如果我使用Person * Bob,则当我使用-> SetName(x,且x为“ abc”字符串或字符串变量)时,SetName(x)函数会出现段错误

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

1 个答案:

答案 0 :(得分:2)

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

这应该有效。

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

完成后,释放内存。

delete Bob;