为什么我C++得到这个随机的奇怪数字
Why I get this random weird number C++
我是使用 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) {}
};
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 将随机生成的数字添加到数组 + 对这些数组求平均值
- 在C++中随机生成 20 个非重复数字
- 为什么我C++得到这个随机的奇怪数字
- C++:创建1000次唯一的随机分布,在任何分布中都没有重复的数字
- 如何编写一个递归函数,以随机的方式混淆从0到6的数字
- 奇怪的数字随机出现在输出中.(C++)
- 生成随机长度的数字字符串
- 随机生成的输出中有多少位数字 1、2、3
- 生成随机字符/数字
- 在随机生成的数组中查找重复的连续数字
- C++ 制作一个随机数字/字母生成器,代码中有问题
- 随机生成数字无法正常工作
- 随机数字双重类型
- 试图从文件中获取随机数字的总和
- 生成加起来为1的随机数字列表
- c++随机数字总是相同的,即使时间(0)作为种子
- C++随机数字游戏,rand正在选择一个不是来自该集的数字
- 生成部分有序的随机数字列表