注册 登录
编程论坛 C++教室

对象数组应用 创建一个程序,要求实现对数组进行赋值。运行结果如下图所示: 2015年6月1日 2015年7月1日 2015年8月1日

柚夏怪 发布于 2016-10-29 09:26, 1792 次点击
#include <iostream>
class DATE
{
  int year;
  int month;
  int day;
 public:
  DATE(int y,int m,int d) :year(y),month(m),day(d){};
};
int main()
{
      DATE a[3] ={
        DATE(2015,6,1),
        DATE(2015,7,1),
        DATE(2015,8,1)
      return 0;
        };
      std::cout<<a[1]<<endl;
}
5 回复
#2
柚夏怪2016-10-29 09:28
怎么实现输出年月日,怎么将输入的年月日分开输出,像展示的那样
#3
炎天2016-10-29 10:59
修改较多
#include <iostream>
using namespace std;
 
struct DATE
{
   short  year,month,day;
   //int month;
   //day;
  //public:
   //DATE(int y,int m,int d) :year(y),month(m),day(d){};
};
 int main()
 {
    DATE a[3] ={
         {2015,6,1},
         {2015,7,1},
         {2015,8,1} };
   
    for(int i=0;i<3;i++)
     {
           
        cout<<(a+i)->year<<"年"<<(a+i)->month<<"月"<<(a+i)->day<<"日"<<endl;
     }      
}
#4
柚夏怪2016-10-29 14:47
回复 3楼 炎天
=====运行开始======
: In function ‘int main()’:
:14: 错误:对‘DATE::DATE(int, int, int)’的调用没有匹配的函数
:3: 附注:备选为: DATE::DATE()
:3: 附注:         DATE::DATE(const DATE&)
:15: 错误:对‘DATE::DATE(int, int, int)’的调用没有匹配的函数
:3: 附注:备选为: DATE::DATE()
:3: 附注:         DATE::DATE(const DATE&)
:16: 错误:对‘DATE::DATE(int, int, int)’的调用没有匹配的函数
:3: 附注:备选为: DATE::DATE()
:3: 附注:         DATE::DATE(const DATE&)
:20: 错误:‘cout’在此作用域中尚未声明
:4: 错误:‘int DATE::year’是私有的
:20: 错误:在此上下文中
:4: 错误:‘int DATE::month’是私有的
:20: 错误:在此上下文中
:4: 错误:‘int DATE::day’是私有的
:20: 错误:在此上下文中
:20: 错误:‘endl’在此作用域中尚未声明

=====运行结束======
#5
炎天2016-10-29 20:29
#include <iostream>
using namespace std;
  
struct DATE
{
    short  year,month,day;
};
   
int main(void)
{
     DATE a[3] ={
          {2015,6,1},
          {2015,7,1},
          {2015,8,1} };
     
     for(int i=0;i<3;i++)
      {
            
         cout<<(a+i)->year<<"年"<<(a+i)->month<<"月"<<(a+i)->day<<"日"<<endl;
      }      
 }
#6
rjsp2016-10-31 08:39
程序代码:
#include <iostream>

class DATE
{
public:
    DATE( int y, int m, int d ) : year(y), month(m), day(d)
    {
    }
private:
    int year;
    int month;
    int day;

    friend std::ostream& operator<<( std::ostream& os, const DATE& dt );
};

std::ostream& operator<<( std::ostream& os, const DATE& dt )
{
    return os << dt.year << "" << dt.month << "" << dt.day;
}

int main( void )
{
    DATE a[3] = { DATE(2015,6,1)
                , DATE(2015,7,1)
                , DATE(2015,8,1) };
    for( size_t i=0; i!=sizeof(a)/sizeof(*a); ++i )
        std::cout << a[i] << std::endl;
    return 0;
}
1