【问题标题】:How do I print only 2 of the specific functions?如何只打印 2 个特定函数?
【发布时间】:2022-11-26 14:21:49
【问题描述】:

我试图只显示功能 1 和 3,但我不知道如何打印它们,因为它只是打印了所有功能。

我需要添加什么才能打印出特定的东西?

#include <iostream>

using namespace std;

class Seminar
{
    int time;
public:
    Seminar()        //Function 1
    {
        time = 30;
        cout << "Seminar starts now" << endl;
    }

    void lecture()        //Function 2
    {
        cout << "Lectures in the seminar on" << endl;
    }

    Seminar(int duration)        //Function 3
    {
        time = duration;
        cout << "Seminar starts now" << endl;
    }

    ~Seminar()        //Function 4
    {
        cout << "Thanks" << endl;
    }
};



int main()
{
    Seminar();
    Seminar(5);
    
    return 0;
}

【问题讨论】:

    标签: c++


    【解决方案1】:

    所有这些都没有被打印出来,函数 2 永远不会被调用。

    运行你的代码给出:

    Seminar starts now
    Thanks
    Seminar starts now
    Thanks
    

    这是预期的,因为

    1. 您调用函数 1:空构造函数(研讨会现在开始)
    2. 这个临时对象被销毁,函数 4:它的析构函数运行(谢谢)
    3. 您调用函数 3:参数构造函数(研讨会现在开始)
    4. 这个临时对象也被销毁,函数 4:它的析构函数再次运行(谢谢)

      并且永远不会读取字段time

      不确定您期望的行为是什么,但是无论哪种方式,请阅读constructors and destructors,因为您似乎对它们有些误解。

    【讨论】:

      猜你喜欢
      • 2021-12-03
      • 2015-12-28
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-28
      • 2021-01-09
      相关资源
      最近更新 更多