使用 ->GetString( " ") 时出现 Seg 错误,它位于单独的类中
Seg Fault when using ->GetString(" ") which is in a separate class
我现在正在练习一些基本的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;
相关文章:
- C++ - 将元素按升序插入数组的 SEG 错误
- 为什么我在使用 istream 迭代器时会出现 seg 错误?
- 字符串上的合并排序上的 Seg 错误
- 导致 Seg 错误的 SingleLinkedList 的析构函数
- g++ 9.2.1 (Linux) 会导致 seg 错误,但 Windows 上的代码块不会
- 函数抛出seg错误,我不知道为什么
- Microsoft Visual Studio 2019交叉编译CMake库 - 有效,但存在SEG错误
- 由于相同的文件名/类名存在于不同的SO中而导致的SEG错误
- 尝试访问 3D 矢量中的元素时出现 Seg 错误
- 垫子对象数组太大会导致 Seg 错误
- 为什么push_back成矢量<矢量<int>>导致 seg 错误?
- 在向量中存储字符串存在 SEG 错误
- 更改本地类名时出现 seg 错误
- 使用 ->GetString( " ") 时出现 Seg 错误,它位于单独的类中
- 将字符数组转换为 std::string 以传递到 std::bitset seg 错误
- 字符和 int 连接何时会导致 seg 错误?
- 静态数组溢出堆栈(seg 错误 11)仅在类定义内部时,否则不会..?
- .EOF 在读取文件时导致 Seg 错误:FIXXED
- 在 qt5 中使用 QSharedPointer 时出现 Seg 错误
- 在c++和Linux中查找总线错误/Seg故障的问题