作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想将优先级值传递给主类和其他类,但是当我这样做时,我得到了错误的优先级值。我不知道哪一部分是错的,因为它对我来说看起来是正确的。当我运行代码时,它返回一个随机数作为优先级值。
#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/
我是一名优秀的程序员,十分优秀!