为什么我会得到这个奇怪的随机数C++; 我对使用C++的指针很新,所以我正在尝试这个小代码,但是问题是当我尝试打印名称< /强>时,我得到这个随机奇怪的数字 364 \ 277 \ 357 \ 376 \ 326 \ 241 + + 310 \ 364 \ 277 \ 357 \ 376 \ 310 < /代码>。这不是内存地址,这让我很困惑,更让我困惑的是,当我用getName()替换name时,它可以完美地工作并打印名称!谢谢你
Person.cpp为什么我会得到这个奇怪的随机数C++; 我对使用C++的指针很新,所以我正在尝试这个小代码,但是问题是当我尝试打印名称< /强>时,我得到这个随机奇怪的数字 364 \ 277 \ 357 \ 376 \ 326 \ 241 + + 310 \ 364 \ 277 \ 357 \ 376 \ 310 < /代码>。这不是内存地址,这让我很困惑,更让我困惑的是,当我用getName()替换name时,它可以完美地工作并打印名称!谢谢你,c++,C++,Person.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(st
#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()
{
}
#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;
}
Person::name
看起来像是std::string*
。在Person::Person(字符串名称,int-Age)
中,通过值传递参数Name
,然后将此局部变量的地址存储在Name
中。当Name
超出范围时,指针会悬空
(这也适用于void Person::setName(字符串名)
)
取消引用Person::name
是未定义的行为,因为它所指向的对象不再存在。解决方案是只存储一个std::string
,而不仅仅是一个指向它的指针
所以你得到的是
class Person {
private:
std::string name;
int age;
public:
Person(std::string Name, int Age) : name(Name), age(Age) {}
};
请阅读并阅读编译器和调试器的文档。如果使用,请使用所有警告和调试信息进行编译,因此
g++-Wall-Wextra-g
然后使用。更喜欢和标准,同时也要意识到使用getName()
是非常不幸和令人困惑的。它可能与stackpointer的位置有关,因此悬挂的指针恰好指向“正确的位置”。这没关系,这是未定义的行为,应该修复。
\364\277\357\376\326\241+\310\364\277\357\376\310 21 2211 11
class Person {
private:
std::string name;
int age;
public:
Person(std::string Name, int Age) : name(Name), age(Age) {}
};