C++编程调试秘笈----带有初始化的基本类型
建议不要使用内置类型,而是使用类
比如:
不要使用int,而是使用Int
不要使用unsigned,该用Unsigned
.....
这样就不会出现所谓的垃圾值
scpp_types.h:
[cpp]
#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环境):
[cpp]
#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;
}
补充:软件开发 , C++ ,