C++编程调试秘笈----读书笔记(5)

五、带有初始化的基本类型

建议不要使用内置类型,而是使用类

比如:

不要使用int,而是使用Int

不要使用unsigned,该用Unsigned

.....

这样就不会出现所谓的垃圾值

scpp_types.h:

#ifndef __SCCP_TYPES_H__
#define __SCCP_TYPES_H__

#include <ostream>
#include "scpp_assert.h"

template <typename T>
class TNumber
{
public:
	TNumber(const T& x =0 )
		:data_(x)
	{

	}
	operator T() const 
	{
		return data_;
	}

	TNumber &operator = (const T& x)
	{
		data_ = x;
		return *this;
	}

	TNumber operator ++(int)
	{
		TNumber<T> copy(*this);
		++data_;
		return copy;
	}

	TNumber operator ++()
	{
		++data_;
		return *this;
	}

	TNumber& operator += (T x)
	{
		data_ += x;
		return *this;
	}

	TNumber& operator -= (T x)
	{
		data_ -= x;
		return *this;
	}

	TNumber& operator *= (T x)
	{
		data_ *= x;
		return *this;
	}

	TNumber& operator /= (T x)
	{
		SCPP_ASSERT(x != 0, "Attempt to divide by 0");
		data_ /= x;
		return *this;
	}

	T operator / (T x)
	{
		SCPP_ASSERT(x != 0, "Attempt to divide by 0");
		return data_ / x;
	}

private:
	T data_;
};

typedef long long int64;
typedef unsigned long long unsigned64;

typedef TNumber<int>		Int;
typedef TNumber<unsigned>	Unsigned;
typedef TNumber<int64>		Int64;
typedef TNumber<unsigned64> Unsigned64;
typedef TNumber<float>		Float;
typedef TNumber<double>		Double;
typedef TNumber<char>		Char;

class Bool
{
public:
	Bool(bool x = false)
		:data_(x)
	{
	}

	operator bool () const
	{
		return data_;
	}

	Bool& operator = (bool x)
	{
		data_ = x;
		return *this;
	}

	Bool& operator &= (bool x)
	{
		data_ &= x;
		return *this;
	}

	Bool& operator |= (bool x)
	{
		data_ |= x;
		return *this;
	}

private:
	bool data_;
};

inline std::ostream& operator << (std::ostream& os, Bool b)
{
	if (b)
	{
		os << "True";
	}
	else
	{
		os << "False";
	}
	return os;
}


 

测试代码(vs2012+win7环境):

#include "stdafx.h"
#include "scpp_assert.h"
#include "iostream"
#include "scpp_vector.h"
#include "scpp_array.h"
#include "scpp_matrix.h"
#include "algorithm"
#include "scpp_types.h"

int _tmain(int argc, _TCHAR* argv[])
{
	Int dataInt;
	Double dataDouble1(1.2);
	Double dataDouble2;
	Char c;

	std::cout << dataInt << std::endl;
	std::cout << dataDouble1 << std::endl;
	std::cout << dataDouble2 << std::endl;
	std::cout << dataInt++ << std::endl;
	std::cout << ++dataInt << std::endl;
	std::cout << c << std::endl;

	c = 'x';
	std::cout << c << std::endl;
	
//	dataDouble1 /= dataDouble2;
	dataDouble1  = dataDouble1 / dataDouble2;

	return 0;
}


 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值