【问题标题】:How can I format the following console output in a class function implementation file?如何在类函数实现文件中格式化以下控制台输出?
【发布时间】:2014-11-07 09:01:45
【问题描述】:

问题告诉我:

“该类应该有成员函数以下列格式打印日期”

  • 3/15/13 //showShortDate
  • 2013 年 3 月 13 日 //showLongDate
  • 2013 年 3 月 15 日 //showEuroDate

函数实现文件中的以下内容将无法编译并给出"cout : undeclared identifier" 错误。我在主程序 .cpp 文件中有#include <iostream>

// Date.cpp is the Date class function implementation file

    #include "Date.h"


    Date::Date(int m, int d, int y)
    {  month = m;
       day = d;
       year = y;
    }

    Date::Date()
    {
      month = 1;
      day = 1;
      year = 2001;      
    }


    void Date::showShortDate()
    {
      cout << month << "/" << day << "/" << year;
    }
    void Date::showLongDate()
    {
       cout << month << " " << day << ", " << year;

    }
    void Date::showEuroDate()
    {
       cout << day << " " << month << " " << year;
    }

【问题讨论】:

  • 啊,我已经关闭了这个问题,但是链接的东西是错误的。对不起。现在其他人需要对此进行近距离投票,因为它缺乏基础研究。

标签: c++


【解决方案1】:

改成:

void Date::showShortDate()
{
  std::cout << month << "/" << day << "/" << year;
}
void Date::showLongDate()
{
   std::cout << month << " " << day << ", " << year;

}
void Date::showEuroDate()
{
   std::cout << day << " " << month << " " << year;
}

或者using namespace std; 我不推荐这样做。

如果你还没有的话,也包括:#include &lt;iostream&gt;

C++ 中的标准函数基本上是在命名空间中定义的。 该命名空间是std,如果你想访问这些函数,你需要告诉编译器这些函数来自哪里。您可以通过在函数前面添加std:: 来做到这一点。或者告诉它使用 std 命名空间(同样不推荐)。


阅读this,了解命名空间背后的基本理念。

【讨论】:

  • 鉴于 OP 不知道他/她在做什么,因此需要一些解释。
  • @phresnel 我已经更新了答案并包含了他可以阅读关于什么是命名空间的链接。
猜你喜欢
  • 2023-03-28
  • 2021-12-02
  • 1970-01-01
  • 1970-01-01
  • 2013-11-19
  • 2010-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多