静态常量整数成员在class内部直接初始化,否则会出现链接错误。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
template <typename T>
class testClass
{
public:
static const int a = 5;
static const long b = 3L;
static const char c = 'c';
static const double d = 100.1;
};
int main()
{
cout << testClass<int>::a << endl;
cout << testClass<int>::b << endl;
cout << testClass<int>::c << endl;
//下面的语句出错,带有类内初始值设定项的静态数据成员必须具有不可变的常量整型
cout << testClass<int>::d << endl;
system("pause");
return 0;
}
increment(++)实现(前置式及后置式),dereference(*)实现
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class INT
{
friend ostream& operator<<(ostream& os, const INT& i);
public:
INT(int i) :m_i(i) {};
//自增然后得到值
INT& operator++()
{
++(this->m_i);
return *this;
}
//先得到值然后自增
const INT operator++(int)
{
INT temp = *this;
++(this->m_i);
return temp;
}
//取值
int& operator*() const
{
return (int&)m_i;
//下面的语句会出错,因为将int&类型的引用绑定到const int类型的初始值设定项
//return m_i;
}
private:
int m_i;
};
ostream& operator<<(ostream& os, const INT& i)
{
os << '[' << i.m_i << ']' << endl;
return os;
}
int main()
{
INT I(5);
cout << I++;
cout << ++I;
cout << *I;
system("pause");
return 0;
}