如何在类中使用指针 [英] how to use a pointer in a Class
问题描述
我有以下程序可以正常工作,但我想知道我是否可以替换使用new operator的以下行 NumDays * days = new NumDays();
使用另一个更容易兼容的C ++命令。
我问这个问题因为这对我来说比Java更像是一个Java命令而不是C ++
< pre lang =c ++> int main(){
NumDays * days = new NumDays ();
double 小时;
cout<< 输入工作小时数并获得工作日。\ n;
cout<< 输入0以终止序列。\ n;
while ( true ){
cout << 输入小时数<< ENDL;
cin>>小时;
if (小时< 0 ){
cout< ;< 输入无效。请重试。<< ENDL;
继续;
}
如果(小时== 0 ){
cout << 退出...<< endl;
break ;
}
days-> setWorkingHours(小时);
cout<<小时<< 工作时间为<< days-> getDays()<< 工作日。<< endl;
您可以在堆栈上分配NumDays
变量;
NumDays天;
这也意味着你必须改变你在<$上引用方法的方式c $ c>天;
days-> setWorkingHours(小时);
成为
days.setWorkingHours(小时);
希望这会有所帮助
Fredrik
I have the following program that works fine but I want to know if I can replace just the following line that use the " new operator " NumDays *days = new NumDays();
with another easier compatible C++ command.
I am asking this question because this resemble more to me a Java command than a C++
int main() {
NumDays *days = new NumDays();
double hours;
cout << "Enter numberof hours worked and get working days.\n";
cout<< "Enter 0 to terminate the sequence. \n";
while (true) {
cout << "Enter number of hours" << endl;
cin >> hours;
if (hours < 0) {
cout << "Invalid input. Please try again." << endl;
continue;
}
if (hours == 0) {
cout << "Exiting..." <<endl;
break;
}
days->setWorkingHours(hours);
cout << hours << " working hours is " << days->getDays() << " working days." << endl;
You could allocate theNumDays
variable on the stack;
NumDays days;
That would also mean you would have to change the way you reference methods ondays
;
days->setWorkingHours(hours);
becomes
days.setWorkingHours(hours);
Hope this helps
Fredrik
这篇关于如何在类中使用指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!