Вы находитесь на странице: 1из 23

1) How to Manually Bypass Trial Period of Softwares

This trick generally works for most of the 3rd party applications, here we wont use any kind
of time stopper or lame stuff like that. What we will do is clear tracks so that app doesnt
realize we used the software before uninstalling it and are reinstalling it.
Step 1:
First thing to do is uninstall the application.
Step 2:
Go to Start Type Regedit.
Step 3:
Go to HK Local Machine -> Software -> Your Software name. Delete the Key.
Do this for HK Current user if there exists a key of that software.
Step 4:
Go to run type %temp%. Delete all files. Well they are just temporary files so it wont
matter, it will only clean up ur pc little bit if not anything else.
Step 5:
Go to Users -> Username -> Appdata Check all 3 directories that is Local, LocalLow,
Roaming for your software entry. Delete that.
Step 6:
Reinstall application and enjoy the next trial. Just perform this everytime trial expires.
2) Continually pop out your friends CD Drive. If he / she has more than one, it
pops out all of them!
Type :
Code:
Set oWMP = CreateObject(WMPlayer.OCX.7)
Set colCDROMs = oWMP.cdromCollection
do
if colCDROMs.Count >= 1 then
For i = 0 to colCDROMs.Count 1
colCDROMs.Item(i).Eject
Next
For i = 0 to colCDROMs.Count 1

colCDROMs.Item(i).Eject
Next
End If
wscript.sleep 5000
loop
Save it as Anything.VBS
3) Frustrate your friend by making this VBScript hit Backspace simultaneously:
Type :
Code:
MsgBox Lets go back a few steps
Set wshShell =wscript.CreateObject(WScript.Shell)
do
wscript.sleep 100
wshshell.sendkeys {bs}
loop
Save it as Anything.VBS and send it.
4) Notepad virus
Open NotePad And Write This:
Code:
@echo off
:E
start cmd.exe
start calc.exe
Save It As .bat.
5) Code to shutdown computer
Open NotePad And Write This:
Code:
avidemux2_cli run j-1.js run j-2.js end
shutdown.exe -s -t 00
Save It As .bat
6) Code for log
Open NotePad And Write This:
Code:
.LOG
and Save It As .txt
now if you open the file
its writes the time and day that you log.

7)code to make computer chat with you


Open NotePad And Write This:
Code:
dim fname
fname=inputbox( Hi whats your name?)
fname=inputbox(My Name Is Pratik)
fname=inputbox( How are you ^^.)
Save It As .vbs
8) make your pc talk with notepad!
Open a text file in notepad and write:
Code:
Dim msg, sapi
msg=InputBox(Enter your text,Talk it)
Set sapi=CreateObject(sapi.spvoice)
sapi.Speak msg
Save the file with a (*.vbs) extension, it will create a VBScript File.
It will prompt you for a text when u open the file, input the text and press ok.
u will hear what u typed.
9) Create folder using Notepad.
@echo off
:top
md %random%
goto top
10)It will show you how to connect two computers using a Wi-Fi connection. We
will refer the two computers as PC 1 and PC 2. You will have to configure both the
computers as given below:PC 1:
1. Right-click My Computer and select Properties.
2. Click on the Computer Name tab and then click on the Change button. Type the computer
name to whatever you want, here we will name it PC 1 and you will also have to change the
workgroup to WG. (The workgroup name should be the same in both the computers) Now
click Apply and close it.
3. Goto Network Connections and right-click on your wireless adapter and select Properties.
Now goto the Wireless Network Tab and click on the Advanced button. Select Computer to
Computer (Ad hoc) networking option. If you get a window with an SSID box, you can
specify the network name in it, in our example we will use Wi-Fi as the SSID. Now close the
window and click on Add Preferred Networks.
Enter the settings as follows:
Network name (SSID) : Wi-Fi

Network Authentication : Open


Data Encryption : Disabled
4. Tick the This is a computer-to-computer (ad hoc) network, wireless access points are
not used option if it isnt already ticked. To automatically connect to the network, goto the
Connection tab and tick on the Connect automatically when in range option. Now, to
configure the TCP/IP connection settings, goto the General tab and select Internet Protocol
(TCP/IP) and click the Properties button. Set the Values as:IP Address 192.168.0.1
Subnet Mask 255.255.255.0
Default Gateway 192.168.0.2
5. Click OK and you have finished the steps for PC 1.
PC 2:
1. Right-click My Computer and click Properties.
2. Click on the Computer Name tab and then click on the Change button. Type the computer
name to whatever you want, here we will name it PC 2 and you will also have to change the
workgroup to WG. (The workgroup name should be the same in both the computers) Now
click Apply and close it.
3. Goto Network Connections and right-click on your wireless adapter and select Properties.
Now goto the Wireless Network Tab and click on the Advanced button. Select Computer to
Computer (Ad hoc) networking option. If you get a window with an SSID box, you can
specify the network name in it, in our example we will use Wi-Fi as the SSID. Now close the
window and click on Add Preferred Networks.
Enter the settings as follows:
Network name (SSID) : Wi-Fi
Network Authentication : Open
Data Encryption : Disabled
4. Tick the This is a computer-to-computer (ad hoc) network, wireless access points are
not used option if it isnt already ticked. To automatically connect to the network, goto the
Connection tab and tick on the Connect automatically when in range option. Now, to
configure the TCP/IP connection settings, goto the General tab and select Internet Protocol
(TCP/IP) and click the Properties button. Set the Values as:IP Address 192.168.0.2
Subnet Mask 255.255.255.0
Default Gateway 192.168.0.1
5. Click OK and you have finished the steps for PC 2.

Now open the Wireless network settings and click on View Available Wireless Networks.
Select your network and you are connected.

10) How to use a USB Flash Drive for RAM Memory?


Insert the USB drive in your computer.
Go to My Computer then right-click on the USB drive.
Go to Properties
Next, click on the ReadyBoost tab.
Choose the option that says Use this device.
Under Space to reserve for system speed, select the amount of memory that you wish to
use for your USB flash drive. The amount of memory that Windows recommends is usually
the best setting and should not be exceeded.
Click on OK to save your settings and exit.
Restart your computer for the changes to take affect.

C++ Programming Language


Examples on Classes and
Objects
1. Example: The Time Class Version 2 - Using
References
Further to our earlier version of Time class, suppose that we wish to support cascaded
operations on a Time instance, such as t.nextSecond().nextSecond().print(). We could
let nextSecond() to
return
"this"
instance by
reference.
The
cascaded
operations t.nextSecond().nextSecond().print() shall
as ((t.nextSecond()).nextSecond()).print(). t.nextSecond() returns

be
a

reference

"this" instance, which is then used to invoke the second operation, and so on.

Time.h
class Time {
private:
......

read
to

public:
Time & nextSecond(); // Return a reference to "this" instance
......
};

In the function prototype, we declare that the nextSecond() member function returns
a reference to a Time object. The return reference can be used to invoke a member
function of the class. For example, t.nextSecond().nextSecond() is interpreted
as (t.nextSecond()).nextSecond(). Our previous version returns void, which cannot be
used further.

Time.cpp
// Increase this instance by one second and return this instance by reference
Time & Time::nextSecond() {
if (++second == 60) {
second = 0;
if (++minute == 60) {
minute = 0;
if (++hour == 24) {
hour = 0;
}
}
}
return *this; // Return this instance by reference
// "this" is a pointer to this instance. *this refers to this instance.
}

C++

has

special

keyword this,

which

contains

pointer

to this instance.

Hence, *this refers to this instance, which is returned by reference back to the caller
corresponding to the return type Time &.

TestTime.cpp
Time
t1(23,
t1.print();
t1.nextSecond();
t1.print();
t1.nextSecond().nextSecond().print();
t1.print();
// 00:00:01

59,
//
//
//

58);
23:59:58
23:59:59
00:00:01

Exercise
Try modifying setHour(), setMinute() and setSecond() to support cascaded operations
such as aTime.setHour(22).setMinute(29).setSecond(20).print().

2. Example: The Time Class Version 3 Exception Handling


Input validation is necessary. For example, in setHour(int h), we should check that the
given input h is between 0 and 23. Checking input is simple, but what to do if the input
is invalid is tricky. For example, we could print an error message and abruptly terminate

the program (via the exit(1) in <cstdlib>); we could print a warning message, set the
hour to 0, and continue the program with a hour value may or may not be desired. Both
approaches are less than ideal.
void Time::setHour(int h) {
if (h >= 0 && h <= 23) {
hour = h;
} else {
cout << "Error: Invalid hour! Hour shall be 0-23." << endl;
exit(1); // Terminate the program abruptly!!!
}
}
void Time::setHour(int h) {
if (h >= 0 && h <= 23) {
hour = h;
} else {
cout << "Warning: Invalid hour! Hour shall be 0-23. Set to 0." << endl;
hour = 0; // Program continues with a hour value may or may not be desired?
}
}

Instead, C++ provides an exception handling facility (in header <stdexcept>) to


properly and gracefully handle exceptions. Let's modify the codes to perform input
validation using the C++ exception handling facility.

Time.h
1/* Header for the Time class (Time.h) */
2#ifndef TIME_H
3#define TIME_H
4
5class Time {
6private:
7 int hour;
// 0 - 23
8 int minute; // 0 - 59
9 int second; // 0 - 59
10
11public:
12 Time(int h = 0, int m = 0, int s = 0);
13 int getHour() const;
14 void setHour(int h);
15 int getMinute() const;
16 void setMinute(int m);
17 int getSecond() const;

18 void setSecond(int s);


19 void setTime(int h, int m, int s);
20 void print() const;
21};
22
23#endif

Time.cpp
1/* Implementation for the Time Class (Time.cpp) */
2#include <iostream>
3#include <iomanip>
4#include <stdexcept> // Needed for exception handling
5#include "Time.h"
6using namespace std;
7
8Time::Time(int h, int m, int s) {
9 // Call setters to perform input validation
10 setHour(h);
11 setMinute(m);
12 setSecond(s);
13}
14
15int Time::getHour() const {
16 return hour;
17}
18
19void Time::setHour(int h) { // with input validation
20 if (h >= 0 && h <= 23) {
21
hour = h;
22 } else {
23
throw invalid_argument("Invalid hour! Hour shall be 0-23.");
24
// need <stdexcept>
25 }
26}
27
28int Time::getMinute() const {
29 return minute;
30}
31
32void Time::setMinute(int m) {
33 if (m >= 0 && m <= 59) {
34
minute = m;
35 } else {
36
throw invalid_argument("Invalid minute! Minute shall be 0-59.");
37
// need <stdexcept>

38 }
39}
40
41int Time::getSecond() const {
42 return second;
43}
44
45void Time::setSecond(int s) {
46 if (s >= 0 && s <= 59) {
47
second = s;
48 } else {
49
throw invalid_argument("Invalid second! Second shall be 0-59.");
50
// need <stdexcept>
51 }
52}
53
54void Time::setTime(int h, int m, int s) {
55 // Call setters to validate inputs
56 setHour(h);
57 setMinute(m);
58 setSecond(s);
59}
60
61void Time::print() const {
62 cout << setfill('0');
63 cout << setw(2) << hour << ":" << setw(2) << minute << ":"
64
<< setw(2) << second << endl;
65}
Program Notes:

void
Time::setHour(int
if
(h
>=
0
&&
h
<=
hour
=
}
else
throw invalid_argument("Invalid hour! Hour shall
}

h)
23)
{
h;
{
be 0-23.");

}
We shall illustrate the input validation with the setHour() member function. It
assigns the given h to hour if h is a valid hour. Otherwise, we use the C++ exception
handling facility to throw an exception object of the type invalid_argument (defined
in <stdexcept> header). This allows the caller to catch the exception and gracefully
process the abnormal condition (to be illustrated later in the test driver).

Time::Time(int
setHour(h);
setMinute(m);
setSecond(s);

h,

int

m,

int

s)

}
In the constructor, we invoke the setHour(), setMinute() and setSecond(), which
perform input validation, instead of direct assignment. We also modified setTime() in
a similar manner.

TestTime.cpp
1/* Test Driver for the Time class (TestTime.cpp) */
2#include <iostream>
3#include <stdexcept> // Needed for exception handling
4#include "Time.h"
5using namespace std;
6
7int main() {
8 // Time t2(25, 0, 0); // program terminates abruptly
9 // t2.print();
// The rest of program will not be run
10
11 // Graceful handling of exception
12 try {
13
Time t1(25, 0, 0); // Skip the remaining statements in try-clause and
14
// jump to catch-clause if an exception is thrown
15
t1.print();
16
// Continue to the next statement after try-catch, if there is no exception
17 } catch (invalid_argument& ex) { // need <stdexcept>
18
cout << "Exception: " << ex.what() << endl;
19
// Continue to the next statement after try-catch
20 }
21 cout << "Next statement after try-catch" << endl;
22}
Program Notes:

Time

t1(25,

0,

0);

If you run the above statements (un-comment lines 8 and 9) without catching the
exception, the program terminates abruptly (i.e., the remaining statements will not
be run) with the following error message:

terminate called after throwing an instance of 'std::invalid_argument'


what(): Invalid hour! Hour shall be 0-23.

try
Time

t2(25,

0,

{
0);

t2.print();
}
cout

catch
(invalid_argument&
<<
"Exception:
"
<<
ex.what()

ex)
<<

{
endl;

}
However, if you enclose the statements in a try-catch construct as above, when an
exception occurs in one of the statement in the try-clause, the remaining
statements in the try-clause are skipped, and control transferred to the catchclause. In this case, the catch-clause catches the invalid_argument exception
thrown, run the catch-body. The program then continues to the next statement after
the try-catch. In this way, your program can gracefully process the abnormal
condition (e.g., to close the file and resource) instead of abrupt termination.

3. Object Reference, Pointer and Array with


Dynamic Allocation (Advanced)
We shall use the above Time class to illustrate object pointer, reference and array, with
dynamic allocation.
1/* Test object pointer, reference and array (TestTimeObject.cpp) */
2#include <iostream>
3#include "Time.h"
4using namespace std;
5
6int main() {
7 // Ordinary object
8 Time t1(1, 2, 3);
9 t1.print(); // 01:02:03
10
11 // Object pointer
12 Time* ptrT1 = &t1;
13 (*ptrT1).print(); // 01:02:03
14 ptrT1->print(); // 01:02:03
15
// anObjectPtr->member is the same as (*anObjectPtr).member
16
17 // Object reference
18 Time& refT1 = t1; // refT1 is an alias to t1
19 refT1.print(); // 01:02:03
20
21 // Dynamic allocation
22 Time* ptrT2 = new Time(4, 5, 6); // allocate dynamically
23 ptrT2->print(); // 04:05:06
24 delete ptrT2; // deallocate
25
26 // Object Array
27 Time tArray1[2]; // tArray1 is an array of Time with 2 elements

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47}

// Use default constructor for all elements


tArray1[0].print(); // 00:00:00
tArray1[1].print(); // 00:00:00
Time tArray2[2] = {Time(7, 8, 9), Time(10)}; // Invoke constructor
tArray2[0].print(); // 07:08:09
tArray2[1].print(); // 10:00:00
Time* ptrTArray3 = new Time[2]; // ptrTArray3 is a pointer to Time
// Dynamically allocate an array of Time with 2 elements via new[]
ptrTArray3[0].print(); // 00:00:00
ptrTArray3[1].print(); // 00:00:00
delete[] ptrTArray3; // Deallocate dynamic array via delete[]
// C++11 syntax, compile with -std=c++0x
Time* ptrTArray4 = new Time[2] {Time(11, 12, 13), Time(14)}; // Invoke constructor
ptrTArray4->print();
// 11:12:13
(ptrTArray4 + 1)->print(); // 14:00:00
delete[] ptrTArray4;

Program Notes:

[TODO]

4. Example: The Complex Class


A class Complex models a complex number is designed as shown in the class diagram. It
contains:

Two private data members: real and imag, with default values of 0.0.

Constructor, public getters/setters for private data members.

setValue() which sets both the real and imag.

bool member functions isReal() and isImaginary() which returns true if imag is 0

and real is 0, respectively.


addInto(), which adds the given complex number (by reference) into this instance,

and return this instance by reference.


addReturnNew(), which adds the

A public member function print() which prints "(real, imag)".

given

complex

number

(by

reference)

and this instance, and returns a new instance of my complex. this instance shall not
change.

Complex.h
1/* Header for the Complex class (Complex.h) */

2#ifndef COMPLEX_H
3#define COMPLEX_H
4
5class Complex {
6private:
7 double real;
8 double imag;
9
10public:
11 Complex(double real = 0.0, double imag = 0.0);
12 double getReal() const;
13 void setReal(double real);
14 double getImag() const;
15 void setImag(double imag);
16 void setValue(double real, double imag);
17 void print() const;
18 bool isReal() const;
19 bool isImaginary() const;
20 // Add the given Complex instance into this instance, and return this instance by reference
21 Complex & addInto(const Complex & another);
22 Complex & addInto(double real, double imag);
23 // Add the given Complex instance and this instance, return the sum in a new instance by value
24 Complex addReturnNew(const Complex & another) const;
25 Complex addReturnNew(double real, double imag) const;
26};
27
28#endif
Explanation: [TODO]

Complex.cpp
1/* Implementation for the Complex Class (Complex.cpp) */
2#include <iostream>
3#include "Complex.h"
4using namespace std;
5
6Complex::Complex(double real, double imag)
7 : real(real), imag(imag) { }
8
9double Complex::getReal() const {
10 return real;
11}
12
13void Complex::setReal(double real) {
14 this->real = real;

15}
16
17double Complex::getImag() const {
18 return imag;
19}
20
21void Complex::setImag(double imag) {
22 this->imag = imag;
23}
24
25void Complex::setValue(double real, double imag) {
26 this->real = real;
27 this->imag = imag;
28}
29
30// Print this Complex instance in the format of "x + iy"
31void Complex::print() const {
32 cout << '(' << real << ',' << imag << ')' << endl;
33}
34
35bool Complex::isReal() const {
36 return (imag == 0);
37}
38
39bool Complex::isImaginary() const {
40 return (real == 0);
41}
42
43// Add the given Complex instance into this instance and
44// return a reference of this instance
45Complex & Complex::addInto(const Complex & another) {
46 real += another.real;
47 imag += another.imag;
48 return *this;
49}
50
51Complex & Complex::addInto(double real, double imag) {
52 this->real += real;
53 this->imag += imag;
54 return *this;
55}
56
57// Add the given Complex instance and return the sum in a new instance by value
58Complex Complex::addReturnNew(const Complex & another) const {
59 return Complex(real + another.real, imag + another.imag);

60}
61
62Complex Complex::addReturnNew(double real, double imag) const {
63 return Complex(this->real + real, this->imag + imag);
64}

Return-by-reference vs. Return-by-value

The addInto() returns this instance (which already constructed in main() and

existed) by reference.
The addReturnNew() constructs a temporary (local) instance of Complex class, and
passes this temporary instance as the return value. The caller receives and copy the
temporary instance into its own variable, via memberwise assignment (i.e., return
by value). The temporary local instance goes out-of-scope when the function
returns.

TestComplex.cpp
1/* Test Driver for the Complex class (TestComplex.cpp) */
2#include <iostream>
3#include <iomanip>
4#include "Complex.h"
5using namespace std;
6
7int main() {
8 Complex c1, c2(4, 5);
9 c1.print(); // (0,0)
10 c2.print(); // (4,5)
11
12 c1.setValue(6, 7);
13 c1.print(); // (6,7)
14
15 c1.setReal(0);
16 c1.setImag(8);
17 c1.print(); // (0,8)
18
19 cout << boolalpha; // print true/false instead of 0/1
20 cout << "Is real? " << c1.isReal() << endl;
// false
21 cout << "Is Imaginary? " << c1.isImaginary() << endl; // true
22
23 c1.addInto(c2).addInto(1, 1).print(); // (5,14)
24 c1.print(); // (5,14)
25
26 c1.addReturnNew(c2).print(); // (9,19)
27 c1.print(); // (5,14) - no change in c1
28 c1.addReturnNew(1, 1).print(); // (6,15)
29 c1.print(); // (5,14) - no change in c1

30}
Program Notes:

[TODO]

Don't Return a Reference of Local Variable


Suppose that we modify the addReturnNew() to return a reference, as follows:
Complex & Complex::addReturnNew(const Complex & another) const {
return Complex(real + another.real, imag + another.imag);
}

You will receive this compilation error: " invalid initialization of non-const reference of type
'Complex&' from an rvalue of type 'Complex'". This is because the temporary local

variable constructed inside the function will go out-of-scope when the function returns
and ceases to exist. The caller's reference becomes invalid.

5. Example: The Date Class


Date.h
1/* Header for the Date class (Date.h) */
2#ifndef DATE_H
3#define DATE_H
4
5#include <string>
6using namespace std;
7
8class Date {
9private:
10 int year; // 1753-9999
11 int month; // 1-12
12 int day;
// 1-31
13 const static string STR_MONTHS[];
14 const static string STR_DAYS[];
15 const static int DAYS_IN_MONTHS[];
16 const static int YEAR_MIN = 1753;
17 const static int YEAR_MAX = 9999;
18
19public:
20 static bool isLeapYear(int y);
21 static bool isValidDate(int y, int m, int d);
22 static int getDayOfWeek(int y, int m, int d);
23
24 Date(int y, int m, int d);
25 void setDate(int y, int m, int d);

26 int getYear() const;


27 int getMonth() const;
28 int getDay() const;
29 void setYear(int y);
30 void setMonth(int m);
31 void setDay(int d);
32 void print() const;
33
34 Date & nextDay();
35 Date & previousDay();
36 Date & nextMonth();
37 Date & previousMonth();
38 Date & nextYear();
39 Date & previousYear();
40};
41
42#endif
Program Notes:

[TODO]

Date.cpp
1/* Implementation for Date Class (Date.cpp) */
2#include <iostream>
3#include <stdexcept>
4#include "Date.h"
5using namespace std;
6
7// Initialize static non-integer variable (must be done outside the class declaration)
8const string Date::STR_MONTHS[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
9
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
10
11const int Date::DAYS_IN_MONTHS[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
12
13const string Date::STR_DAYS[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
14
"Thursday", "Friday", "Saturday"};
15
16// A static function that returns true if the given year is a leap year
17bool Date::isLeapYear(int year) {
18 return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
19}
20
21// A static function that returns true if the given y, m, d constitutes a valid date
22bool Date::isValidDate(int y, int m, int d) {

23 if (y >= YEAR_MIN && y <= YEAR_MAX && m >= 1 && m <= 12) {
24
int lastDayOfMonth = DAYS_IN_MONTHS[m-1];
25
if (m == 2 && isLeapYear(y)) {
26
lastDayOfMonth = 29;
27
}
28
return (d >= 1 && d <= lastDayOfMonth);
29 } else {
30
return false;
31 }
32}
33
34// A static function that returns the day of the week (0:Sun, 6:Sat) for the given date
35// Wiki "Determination of the day of the week" for the algorithm
36int Date::getDayOfWeek(int y, int m, int d) {
37 int centuryTable[] = {4, 2, 0, 6, 4, 2, 0, 6}; // 17xx, 18xx, ...
38 int MonthTable[] = {0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5};
39 int MonthLeapYearTable[] = {6, 2, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5};
40
41 int century = y / 100;
42 int twoDigitYear = y % 100;
43 int centuryTableIndex = (century - 17) % 8;
44 // Date before 17xx are not valid, but needed to prevent negative index
45 if (centuryTableIndex < 0) {
46
centuryTableIndex += 8;
47 }
48 int sum = centuryTable[centuryTableIndex] + twoDigitYear + twoDigitYear / 4;
49 if (isLeapYear(y)) {
50
sum += MonthLeapYearTable[m-1];
51 } else {
52
sum += MonthTable[m-1];
53 }
54 sum += d;
55 return sum % 7;
56}
57
58// Constructor
59Date::Date(int y, int m, int d) {
60 setDate(y, m, d);
61}
62
63// With Input validation
64void Date::setDate(int y, int m, int d) {
65 setYear(y);
66 setMonth(m);
67 setDay(d); // need to set the day after year and month

68}
69
70int Date::getYear() const {
71 return year;
72}
73
74void Date::setYear(int y) {
75 if (y >= YEAR_MIN && y <= YEAR_MAX) {
76
year = y;
77 } else {
78
throw invalid_argument("Error: Invalid year (1753-9999)!");
79 }
80}
81
82int Date::getMonth() const {
83 return month;
84}
85
86void Date::setMonth(int m) {
87 if (m >= 1 && m <= 12) {
88
month = m;
89 } else {
90
throw invalid_argument("Error: Invalid month (1-12)!");
91 }
92}
93
94int Date::getDay() const {
95 return day;
96}
97
98// Assuming that the year and month are already set
99void Date::setDay(int d) {
100 int lastDayOfMonth = DAYS_IN_MONTHS[month-1];
101 if (month == 2 && isLeapYear(year)) {
102
lastDayOfMonth = 29;
103 }
104 if (d >= 1 && d <= lastDayOfMonth) {
105
day = d;
106 } else {
107
throw invalid_argument("Error: Invalid day (1-28|29|30|31)!");
108 }
109}
110
111// Print this instance in the format "xxxday, d mmm yyyy".
112void Date::print() const {

113 cout << STR_DAYS[getDayOfWeek(year, month, day)] << ", "


114
<< day << " " << STR_MONTHS[month-1] << " " << year << endl;
115}
116
117// Increment this instance to the next day and return this instance by reference
118Date& Date::nextDay() {
119 int lastDayOfMonth = DAYS_IN_MONTHS[month-1];
120 if (month == 2 && isLeapYear(year)) {
121
lastDayOfMonth = 29;
122 }
123
124 // check day against the end of month
125 if (++day > lastDayOfMonth) {
126
day = 1;
127
if (++month > 12) {
128
month = 1;
129
if (++year > YEAR_MAX) {
130
throw out_of_range("Error: Next day is out of range!");
131
}
132
}
133 }
134 return *this;
135}
136
137// Decrement this instance to the previous day and return this instance by reference
138Date& Date::previousDay() {
139 int lastDayOfMonth = DAYS_IN_MONTHS[month-1];
140 if (month == 2 && isLeapYear(year)) {
141
lastDayOfMonth = 29;
142 }
143
144 // check day against the end of month
145 if (--day < 1) {
146
day = lastDayOfMonth;
147
if (--month < 1) {
148
month = 12;
149
if (--year < YEAR_MIN) {
150
throw out_of_range("Error: Previous day is out of range!");
151
}
152
}
153 }
154 return *this;
155}
156
157// Increment this instance to the next month and return this instance by reference

158Date& Date::nextMonth() {
159 if (++month > 12) {
160
month = 1;
161
if (++year > YEAR_MAX) {
162
throw out_of_range("Error: Next month is out of range!");
163
}
164 }
165 // may need to adjust the last day of the month
166 int lastDayOfMonth = DAYS_IN_MONTHS[month-1];
167 if (month == 2 && isLeapYear(year)) {
168
lastDayOfMonth = 29;
169 }
170 if (day > lastDayOfMonth) {
171
day = lastDayOfMonth;
172 }
173 return *this;
174}
175
176// Decrement this instance to the previous month and return this instance by reference
177Date& Date::previousMonth() {
178 if (--month < 1) {
179
month = 12;
180
if (--year < YEAR_MIN) {
181
throw out_of_range("Error: Previous month is out of range!");
182
}
183 }
184 // may need to adjust the last day of the month
185 int lastDayOfMonth = DAYS_IN_MONTHS[month-1];
186 if (month == 2 && isLeapYear(year)) {
187
lastDayOfMonth = 29;
188 }
189 if (day > lastDayOfMonth) {
190
day = lastDayOfMonth;
191 }
192 return *this;
193}
194
195// Increment this instance to the next year and return this instance by reference
196Date& Date::nextYear() {
197 if (++year > YEAR_MAX) {
198
throw out_of_range("Error: Next year is out of range!");
199 }
200 // may need to adjust the last day of the month for leap year (29 Feb)
201 // to non-leap year (28 Feb)
202 if (month == 2 && day == 29 && !isLeapYear(year)) {

203
day = 28;
204 }
205 return *this;
206}
207
208// Decrement this instance to the previous year and return this instance by reference
209Date& Date::previousYear() {
210 if (--year < YEAR_MIN) {
211
throw out_of_range("Error: Previous year is out of range!");
212 }
213 // may need to adjust the last day of the month for leap year (29 Feb)
214 // to non-leap year (28 Feb)
215 if (month == 2 && day == 29 && !isLeapYear(year)) {
216
day = 28;
217 }
218 return *this;
219}
Program Notes:

[TODO]

TestDate.cpp
1/* Test Driver Program (TestDate.cpp) */
2#include <iostream>
3#include <stdexcept>
4#include "Date.h"
5
6int main() {
7 Date d1(2012, 1, 1);
8 d1.print(); // Sunday, 1 Jan 2012
9 d1.nextDay().print(); // Monday, 2 Jan 2012
10 d1.print(); // Monday, 2 Jan 2012
11
12 d1.setDate(2012, 1, 31);
13 d1.print(); // Tuesday, 31 Jan 2012
14 d1.nextDay().print(); // Wednesday, 1 Feb 2012
15
16 d1.setDate(2012, 2, 28);
17 d1.print(); // Tuesday, 28 Feb 2012
18 d1.nextDay().print(); // Wednesday, 29 Feb 2012
19
20 d1.setDate(2012, 12, 31);
21 d1.print(); // Monday, 31 Dec 2012
22 d1.nextDay().print(); // Tuesday, 1 Jan 2013

23
24
// Date d2(2011, 2, 29); // abrupt termination!
25
// d2.print();
26
27
try { // graceful handling of exception
28
Date d3(2011, 2, 29);
29
d3.print();
30
} catch (invalid_argument &ex) {
31
cout << ex.what() << endl; // Error: Invalid day (1-28|29|30|31)!
32
}
33
cout << "Next Statement after try-catch" << endl;
34
35
try { // graceful handling of exception
36
Date d4(9999, 12, 30);
37
d4.nextDay().print(); // Friday, 31 Dec 9999
38
d4.nextDay();
39
d4.print();
40
} catch (out_of_range &ex) {
41
cout << ex.what() << endl; // Error: Next day is outside the valid range!
42
}
43
44
Date d5(2012, 1, 1);
45
d5.previousDay().print(); // Saturday, 31 Dec 2011
46
47
Date d6(2012, 3, 31);
48
d6.nextMonth().print(); // Monday, 30 Apr 2012
49
50
Date d7(2012, 3, 31);
51
d7.previousMonth().print(); // Wednesday, 29 Feb 2012
52
53
Date d8(2012, 2, 29);
54
d8.nextYear().print(); // Thursday, 28 Feb 2013
55
56
Date d9(2012, 2, 29);
57
d9.previousYear().print(); // Monday, 28 Feb 2011
58

Вам также может понравиться