gpt4 book ai didi

c++ - 类的实例只允许 1 个方法,否则程序崩溃

转载 作者:行者123 更新时间:2023-11-30 01:12:51 24 4
gpt4 key购买 nike

我正在学习类(class)和 OOP,所以我正在做一些练习程序,当我在编程时遇到最奇怪的错误。

因此,我有以下文件,以我的类“pessoa”开头,位于 pessoa.h 中:

#pragma once
#include <string>
#include <iostream>

using namespace std;

class pessoa {
public:
//constructor (nome do aluno, data de nascimento)
pessoa(string newname="asffaf", unsigned int newdate=1996): name(newname), DataN(newdate){};
void SetName(string a); //set name
void SetBornDate(unsigned int ); //nascimento
string GetName(); //get name
unsigned int GetBornDate();
virtual void Print(){}; // print

private:
string name; //nome
unsigned int DataN; //data de nascimento
};

谁的函数定义在pessoa.cpp

#include "pessoa.h"

string pessoa::GetName ()
{
return name;
}

void pessoa::SetName(string a)
{
name = a;
}

unsigned int pessoa::GetBornDate()
{
return DataN;
}

void pessoa::SetBornDate(unsigned int n)
{
DataN=n;
}

一个函数 DoArray,在 DoArray.h 中声明,并在文件 DoArray.cpp 中定义:

    pessoa** DoArray(int n)
{
pessoa* p= new pessoa[n];
pessoa** pointer= &p;
return pointer;
}

和主文件:

#include <string>
#include <iostream>
#include "pessoa.h"
#include "DoArray.h"
#include <cstdio>

using namespace std;

int main()
{
//pessoa P[10];
//cout << P[5].GetBornDate();
pessoa** a=DoArray(5);
cerr << endl << a[0][3].GetBornDate() << endl;
cerr << endl << a[0][3].GetName() << endl;


return 0;
}

奇怪的发现是,如果我对上述方法之一“GetBornDate”或 GetName 进行注释并运行,未注释的方法将按预期正常运行。但是,如果两者都没有注释,那么第一个将运行,程序将在第二个方法之前崩溃。

抱歉发了这么长的帖子。

最佳答案

让我们看看这个函数:

int *get()
{
int i = 0;
return &i;
}

它有什么问题?它返回指向局部变量的指针,该变量在函数 get() 终止时不再存在,即它返回悬空指针。现在你的代码:

 pessoa** DoArray(int n)
{
pessoa* p= new pessoa[n];
return &p;
}

你看到问题了吗?

进一步澄清:

 typedef pessoa * pessoa_ptr;
pessoa_ptr* DoArray(int n)
{
pessoa_ptr p= whatever;
return &p;
}

您需要了解,无论您分配给 p 什么,都不会改变 p 本身的生命周期。指针与其他变量相同。

关于c++ - 类的实例只允许 1 个方法,否则程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33398463/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com