用c++编写一个带有构造函数的日期类,使用print成员函数输出。
时间: 2024-03-10 19:49:13 浏览: 112
好的,以下是用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
```
相关问题
用c++编写一个带有构造函数的日期类。使用 print() 成员函数输出日期
好的,下面是一个带有构造函数的日期类,并且定义了一个 print() 成员函数来输出日期的 C++ 代码:
```cpp
#include <iostream>
using namespace std;
class Date {
public:
Date(int year, int month, int day) : year(year), month(month), day(day) {}
void print() {
cout << year << "/" << month << "/" << day << endl;
}
private:
int year, month, day;
};
```
在上面的代码中,我们定义了一个名为 Date 的类,它有一个构造函数,需要传入三个参数:年、月、日。构造函数使用成员初始化列表将这些参数存储在对象的属性中。我们还定义了一个名为 print() 的成员函数,它使用 cout 输出对象的属性,格式为日期格式。
我们可以使用以下代码创建一个 Date 对象,并调用 print() 函数输出日期:
```cpp
Date d(2022, 1, 1);
d.print(); // 输出:2022/1/1
```
注意,在 C++ 中,我们使用类的访问修饰符将类的属性和方法分为公有(public)、私有(private)和保护(protected)三种。在上面的代码中,我们使用了公有成员函数print()来输出日期,而将年、月、日三个属性声明为私有(private)属性。这样一来,外部代码就不能直接访问和修改这些属性,只能通过类的公有方法来操作。
用c++编写一个带有拷贝构造函数的点类,使用成员函数输出数据成员的值。
好的,我来为您编写一个带有拷贝构造函数的点类,如下所示:
```cpp
#include <iostream>
class Point {
public:
// 构造函数
Point(int x = 0, int y = 0) {
this->x = x;
this->y = y;
}
// 拷贝构造函数
Point(const Point& other) {
this->x = other.x;
this->y = other.y;
}
// 成员函数,输出数据成员的值
void print() {
std::cout << "x = " << x << ", y = " << y << std::endl;
}
private:
int x; // x坐标
int y; // y坐标
};
```
这个点类有两个数据成员(x和y),一个构造函数,一个拷贝构造函数和一个输出数据成员的值的成员函数print()。在构造函数中,我们可以给x和y赋初值,而在拷贝构造函数中,我们可以将other的x和y值赋给当前对象的x和y值。最后,print()函数可以输出当前对象的x和y值。
阅读全文
相关推荐














