【问题标题】:Why my object seems to be created two times?为什么我的对象似乎被创建了两次?
【发布时间】:2017-03-19 10:15:07
【问题描述】:

所以我今天正在学习一些课程,我对如何显示功能感到困惑

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;
}

现在当我运行程序时它工作正常,但问题是构造函数和破坏显示两次。

Photo of the output

Full code

【问题讨论】:

  • 完整代码不可用。
  • 问问自己dateType()main 中的实际作用。

标签: c++ class constructor destructor


【解决方案1】:

这是因为你创建的对象在调用 setDate() 方法后被销毁了,因为 main 中没有它的标识符。你刚刚创建了它,调用了一个方法,然后就结束了。 你做到了:

dateType().setDate();

所以当您执行 dateType() 时会创建 dataType 对象。但是在它的 setDate() 方法被调用之后,它就被销毁了,因为你没有将它保存在任何地方。

尝试做:

dateType p;
p.setDate();

这一次它不会被摧毁。

【讨论】:

  • 嘿你能帮我吗,为什么它的输出加倍,如果我输入 2,4,6,9,11。 31 会出现.. double display
  • 我已经声明了闰年,所以不需要我把它们放进去。
  • 从else中删除条件,如果“if”和“else if”没有运行,else会自动运行。我们在 else 中没有任何条件。您可以查看此视频教程以了解其工作原理。 youtube.com/watch?v=zbcdzXEN5kQ
  • 哦,我的错误是没有关注我的代码,再次感谢您
猜你喜欢
  • 2014-01-08
  • 2020-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多