为什么我C++得到这个随机的奇怪数字

Why I get this random weird number C++

本文关键字:随机 数字 C++ 为什么      更新时间:2023-10-16

我是使用 c++ 的指针的新手,所以我正在尝试这个小代码,但问题是当我尝试打印名称时,我得到了这个随机奇怪的数字364277357376326241+ 310364277357376310。这不是内存地址,这令人困惑,更让我困惑的是,当我用getName((替换name时,它可以完美运行并打印名称!谢谢!!

人.cpp

#include "Pesron.hpp"
#include <string>
#include <iostream>
using namespace std;
Person:: Person()
{
}
Person::Person(string Name, int Age)
{
name=&Name;
age=Age;
}
void Person:: setName(string Name)
{
name=&Name;
}
void Person:: setAge(int Age)
{
age=Age;
}
string Person:: getName()
{
return *name;
}
int Person:: getAge()
{
return age;
}
void Person:: display()
{
cout<<*name<<" "<<age<<" ";
}
Person::~Person()
{
}

学生.cpp

#include "Student.hpp"
Student:: Student(string Name, int  Age,int Grades, int ID):Person(Name , Age)
{
grades=Grades;
id=ID;
}
void Student:: setId(int ID)
{
id=ID;
}
int Student:: getId()
{
return id;
}
void Student:: setGrades(int Grades )
{
grades= Grades;
}
int Student:: getGrades()
{
return grades;
}
void Student:: display()
{
Person::display();
cout<<grades<<" "<<id<<endl;
}

主.cpp

#include "Pesron.hpp"
#include "Student.hpp"
#include "graduteStudent.hpp"
#include <iostream>
int main(int argc, const char * argv[]) {
// insert code here...
Student student("ZAID",21,2211,11);
student.display();
return 0;
}

输出

364277357376326241+310364277357376310 21 2211 11

Person::name看起来像是一个std::string *。在Person::Person(string Name, int Age)中,按值传递参数Name,然后将此局部变量的地址存储在name中。当Name超出范围时,您有一个悬空的指针。

(这也适用于void Person::setName(string Name)(

取消引用Person::name是未定义的行为,因为它指向的对象不再存在。解决方案是简单地存储一个std::string,而不仅仅是指向它的指针。

所以你会得到类似的东西

class Person {
private:
std::string name;
int age;
public:
Person(std::string Name, int Age) : name(Name), age(Age) {}
};