用C++创建一个date类,有年、月、日的属性及带参数的构造函数
时间: 2024-05-10 12:19:01 浏览: 21
以下是一个简单的示例代码,实现了一个包含年、月、日属性和带参数的构造函数的date类:
```cpp
#include<iostream>
using namespace std;
class date{
private:
int year,month,day;
public:
date(int y,int m,int d){
year=y;
month=m;
day=d;
}
void display(){
cout<<year<<"-"<<month<<"-"<<day<<endl;
}
};
int main(){
date d(2021,9,10);
d.display();
return 0;
}
```
在这个例子中,我们定义了一个date类,有年、月、日三个私有属性。接下来,我们定义了一个带参数的构造函数,用于初始化对象的属性。最后,我们实现了一个display()函数,用于在控制台打印对象的属性。
在main函数中,我们创建了一个名为d的date对象,并将年、月、日分别设置为2021、9、10。我们调用对象的display()函数,打印出对象的属性。输出结果为:2021-9-10。
相关问题
请用c++写一个类,包含年月日及默认构造函数
好的,以下是一个用C++编写的包含年月日及默认构造函数的类的示例代码:
```cpp
#include <iostream>
class Date {
private:
int year;
int month;
int day;
public:
Date() {
year = 0;
month = 0;
day = 0;
}
void setYear(int y) {
year = y;
}
void setMonth(int m) {
month = m;
}
void setDay(int d) {
day = d;
}
int getYear() const {
return year;
}
int getMonth() const {
return month;
}
int getDay() const {
return day;
}
};
int main() {
Date date;
std::cout << "默认构造函数创建的日期:" << std::endl;
std::cout << "年份: " << date.getYear() << std::endl;
std::cout << "月份: " << date.getMonth() << std::endl;
std::cout << "日期: " << date.getDay() << std::endl;
return 0;
}
```
在这个示例中,我们定义了一个名为`Date`的类,它包含了私有的`year`、`month`和`day`成员变量,以及公有的默认构造函数和一些成员函数来设置和获取这些成员变量的值。
默认构造函数被定义为没有参数的函数,并在内部将`year`、`month`和`day`初始化为0。
在`main`函数中,我们创建了一个名为`date`的`Date`对象,并输出其成员变量的值。
希望这个示例对你有帮助!如果还有其他问题,请随时提问。
用c++编写一个带有构造函数的日期类,使用print成员函数输出。
好的,以下是用C++编写的日期类代码示例:
```cpp
#include <iostream>
using namespace std;
class Date {
private:
int year;
int month;
int day;
public:
// 构造函数
Date(int y, int m, int d) {
year = y;
month = m;
day = d;
}
// 输出日期
void print() {
cout << year << "-" << month << "-" << day << endl;
}
};
int main() {
// 创建日期对象
Date date(2021, 7, 12);
// 输出日期
date.print();
return 0;
}
```
在这个日期类中,构造函数被定义为带有三个参数的函数,分别表示年份、月份和日期。print() 成员函数用于输出日期。在主函数中,我们创建了一个日期对象,并使用 print() 函数输出日期。
输出结果为:
```
2021-7-12
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)