c++ - 使用单独类中的 ->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;
}
解决方案
如果你声明一个指针变量,你需要先用一个有效的实例来填充它。否则,它指向无效内存,您将遇到您遇到的内存故障。
这应该有效。
Person* Bob = new Person();
Bob->SetName("Bob");
Bob->SetMoney(3000);
完成后,释放内存。
delete Bob;
推荐阅读
- python-3.x - 地理地图上的 Matplotlib 散点图,隐藏背景
- javascript - 删除值取消选择选择jQuery
- java - 列出已执行 Java 应用程序的已加载模块
- javascript - 如何避免 TypeScript 中出现虚假的“未使用参数”警告
- android - 如何更改 Fotoapparat 相机中的图片分辨率?
- python - 如何使用 BeautifulSoup 使用表 id 提取表
- jira - 如何通过 BOT 登录 jira?
- c++ - 执行时预期的不合格 ID -> [0]
- ajax - 如何在html头中写入token以及如何使用?
- clojure - Clojure 读取字符串