首页 > 解决方案 > 使用单独类中的 ->GetString(" ") 时出现段错误

问题描述

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

当我使用“Person Bob”创建对象并使用“。” 代码工作正常,但是如果我使用 Person* Bob,SetName(x) 函数段错误,当我使用 ->SetName(x, x 是“abc”字符串或字符串变量时

主文件


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

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

个人.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;
}

标签: c++

解决方案


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

这应该有效。

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

完成后,释放内存。

delete Bob;

推荐阅读