C++ 为什么我的对象似乎被创建了两次?
所以我今天正在学习一些课程,我对如何显示函数感到困惑C++ 为什么我的对象似乎被创建了两次?,c++,class,constructor,destructor,C++,Class,Constructor,Destructor,所以我今天正在学习一些课程,我对如何显示函数感到困惑 dateType::dateType() { cout<<"Object Created\n"; } void dateType::setDate() { cout<<"Enter Month: "; cin>>month; cout<<endl; cout<<"Enter Date: "; cin>>day; c
dateType::dateType()
{
cout<<"Object Created\n";
}
void dateType::setDate()
{
cout<<"Enter Month: ";
cin>>month;
cout<<endl;
cout<<"Enter Date: ";
cin>>day;
cout<<endl;
cout<<"Enter Year: ";
cin>>year;
cout<<endl;
}
.....
//other function declaration to access the private
.....
void dateType:: printdate()
{
cout<<"Month: "<<month<<endl;
cout<<"Date: "<<day<<endl;
cout<<"Year: "<<year<<endl;
cout<<"Leap Year: \n"<<endl;
}
dateType::~dateType()
{
cout<<"Object Deleted";
}
int main()
{
dateType().setDate();
dateType().printdate();
return 0;
}
dateType::dateType()
{
cout这是因为您创建的对象在调用setDate()方法后被销毁,因为main中没有它的标识符。您只是创建了它,调用了一个方法,然后就结束了。
你做到了:
dateType().setDate()
因此,在执行dateType()时会创建dataType对象。但在调用其setDate()方法后,它会被销毁,因为您没有将其保存在任何位置
试着做:
dateType p;
p.setDate();
这次它不会被销毁。完整代码不可用。问问自己表达式dateType()是什么
实际上在main
中有。嘿,你能帮我一下吗,如果我输入2,4,6,9,11,为什么它的输出会加倍。31将显示..我已经声明了闰年,所以不需要将它们放入。从else中删除条件,if和else if不运行,else将自动运行。我们在else中没有任何条件。您可以查看此视频教程以了解其工作原理。噢,我的坏消息没有支付我的代码。再次感谢您