gpt4 book ai didi

c++ - 我是否以错误的方式声明了 getpriorityvalues 函数?

转载 作者:行者123 更新时间:2023-11-27 23:36:56 26 4
gpt4 key购买 nike

我想将优先级值传递给主类和其他类,但是当我这样做时,我得到了错误的优先级值。我不知道哪一部分是错的,因为它对我来说看起来是正确的。当我运行代码时,它返回一个随机数作为优先级值。

#include <iostream>
#include <string>
using namespace std;

class Process {

private:
int ID; //I decleare variables
int priority;
int arrivaltime;
int runtime;

public:
Process(int id = -1, int p = 4, int arr = 0, int run = 0); //initiliazing
int getpriorityvalues();
};
//contsructor
Process::Process(int id, int p, int arr, int run)
{
int ID = id;
int priority = p;
int arrivaltime = arr;
int runtime = run;
cout << ID;
cout << priority; //returning priority variable
}
//function that I want to use for variable passing
int Process::getpriorityvalues()
{
cout << priority;
cout << ID;
cout << arrivaltime;
cout << runtime;
return priority;
}

#include <iostream>
#include "Process.h"
using namespace std;

int main()
{

Process A; //object A
int b = A.getpriorityvalues(); //result is not -4
cout << b; //it is random number

return 0;
}

最佳答案

在你的构造函数中你没有初始化成员变量,你正在创建局部变量,这些变量在构造函数返回时被销毁。

在构造函数上使用初始化列表:

Process::Process (int id,int p,int arr,int run)
: ID{id},
priority{p},
arrivaltime{ar},
runtime{run}
{
cout<< ID;
cout<<priority; //returning priority variable
}

关于c++ - 我是否以错误的方式声明了 getpriorityvalues 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58574182/

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