C++大学基础教程_10_5_使用this指针

//testMain1.cpp
//隐式和显式使用this指针来访问对象的数据成员

#include <iostream>
using namespace std;
class Test
{
public:
	Test(int = 0);
	void print() const;
private:
	int x;
};

Test::Test(int val)
	:x(val)
{}//空函数体

void Test::print() const
{
	cout << "x = " << x << endl;                       
	cout << "this->x = " << this->x << endl;     //两种表示方法,谨记
	cout << "(*this).x = " << (*this).x << endl;
}

int main()
{
	Test shortTest(9);
	shortTest.print();
	system("pause >> cout");
	return 0;
}

//Time.h

#ifndef TIME_H_
#define TIME_H_

class Time
{
public:
	Time(int = 0,int = 0,int = 0);
	Time &setTime(int,int,int);
	Time &setHour(int);
	Time &setMinute(int);
	Time &setSecond(int);

	int getHour() const;
	int getMinute() const;
	int getSecond() const;

	void printUniversal() const;//传统的计时方式,0-23时
	void printStandard() const;//普遍的计时方式0-12;AM,PM
private:
	int hour;//0-23
	int minute;//0-59
	int second;//0-59
};

#endif
//Time.cpp
#include "Time.h"
#include <iostream>
#include <iomanip> /*using std::setfill   using std::setw*/
using namespace std;

Time::Time(int h,int m,int s)
{
	setTime(h,m,s);
}

Time &Time::setTime(int h,int m,int s)
{
	setHour(h);
	setMinute(m);
	setSecond(s);
	return *this;
}

Time &Time::setHour(int h)
{
	hour = (h>=0&&h<24)? h:0;
	return *this;
}

Time &Time::setMinute(int m)
{
	minute = (m>=00&&m<60)? m:0;
	return *this;
}

Time &Time::setSecond(int s)
{
	second = (s>=0&&s<60)? s:0;
	return *this;
}

int Time::getHour() const
{
	return hour;
}
int Time::getMinute() const
{
	return minute;
}
int Time::getSecond() const
{
	return second;
}

void Time::printUniversal() const   //HH:MM:SS
{
	cout << setfill('0') << setw(2) << getHour() << ":" 
	       << setw(2)<< getMinute() << ":" 
		   << setw(2) << getSecond() << endl;
}

void Time::printStandard() const
{
	cout << setfill('0') << setw(2)
		   << ((getHour()==0 || getHour()==12)? 12:hour%12) << ":"
		   << setw(2) << getMinute() << ":" 
		   << setw(2) << getSecond() << (getHour()<12 ? "AM":"PM")
		   << endl;
}
//testMain2.cpp
//使用this指针使串联的函数调用成为可能

#include "Time.h"
#include <iostream>
using namespace std;
int main()
{
	Time t;
    
	//使用this指针使串联的函数调用!!!
	t.setHour(18).setMinute(45).setSecond(32);
	cout << "Universal time: ";
	t.printUniversal();
	cout << "Standard time: ";
	t.printStandard();

	system("pause >> cout ");
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值