#include<iostream>
using namespace std;
class Date {
int Day;
int Month;
int Year;
public:
void setDay(int day) {
if(day>=1 && day<=31)
Day = day;
}
int getDay() {
return Day;
}
void setMonth(int month) {
if(month <= 12)
Month = month;
}
int getMonth() {
return Month;
}
void setYear(int year) {
if(year >=1111)
Year = year;
}
int getYear() {
return Year;
}
void DisplayDate()
{
cout << "Days: " << Day << " \n";
cout << "Month: " << Month << " \n";
cout << "Year: " << Year << " \n";
}
Date(int day, int month, int year) {
Day = day;
Month = month;
Year = year;
}
void Birthday()
{
cout << "Your Birthday is " << Day << " / " << Month << " / " << Year << "\n";
}
};
int main()
{
Date date1 = Date(10, 10, 2000);
date1.DisplayDate();
date1.Birthday();
}
此代碼用于輸入日期年月。如何添加cin函式來要求用戶輸入他的資料?我曾嘗試添加cin我的主要功能,但它為我提供了很多錯誤。
uj5u.com熱心網友回復:
您可以簡單地撰寫一個建構式,它從任何std::istream物件(如std::cin.
只需將建構式添加到您的類中:
class Date {
int Day;
int Month;
int Year;
public:
Date( std::istream& is )
{
std::cout << "Please enter day" << std::endl;
is >> Day;
std::cout << "Please enter Month" << std::endl;
is >> Month;
std::cout << "Please enter Year" << std::endl;
is >> Year;
}
... REST OF YOUR CLASS ...
};
int main()
{
//Date date1 = Date(10, 10, 2000);
// Construct your object with the constructor and the `std::cin` object
Date date1{ std::cin };
date1.DisplayDate();
date1.Birthday();
}
現在,您還可以從檔案或任何其他std::istream. 如果你喜歡 o 也從檔案中讀取,那么輸出到std::cout請求的引數是沒有意義的:-)
uj5u.com熱心網友回復:
我假設你做了類似的事情
cin >> date1.Day >> date2.Month >> date3.Year
,這顯然是行不通的,因為你的變數是私有的。將它們設為公開或將它們輸入到其他變數中并使用方法設定它們的值。
uj5u.com熱心網友回復:
不知道你遇到了什么問題,你能列出你遇到的錯誤嗎?你應該可以只寫int day; cin >> day;.
uj5u.com熱心網友回復:
無法理解您的問題是什么。您只需要添加cin物件來要求用戶輸入他們的資料,如下所示:
int main()
{
int day=0, month=0, year=0;
cout << "plearse enter day month year" << endl;
cin >> day >> month >> year;
Date date1 = Date(day, month, year);
date1.DisplayDate();
date1.Birthday();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/359080.html
上一篇:查詢屬性名稱及其類
