学习内容:
1.测试命名空间
2.函数模板
3.随机数种子
4.指针非法赋值
5.转换函数
#include <iostream>
#include <string.h>
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;
class Time
{
public:
Time()
{
m_i = 2024;
m_j = 5.22;
}
friend ostream& operator<<(ostream &os, const Time& t);
Time operator*(double m) const;
friend Time operator*(double m, const Time& t)
{
return t * m;
}
private:
int m_i;
double m_j;
};
Time Time::operator*(double m) const
{
Time result;
result.m_i = m + 10;
result.m_j = m * 2;
return result;
}
ostream& operator<<(ostream& os, const Time& t)
{
os << "m_i = " << t.m_i << endl << "m_j = " << t.m_j << endl;;
return os;
}
namespace VEC
{
void test1()
{
cout << "VEC" << endl;
}
}
namespace LIST
{
void test1()
{
cout << "LIST" << endl;
}
}
namespace TESTFILENAME
{
template
<typename T>
void save(const T& t)
{
cout << t.filename() << endl;
}
}
struct CLA1
{
string filename() const
{
return "CLA1";
}
};
struct CLA2
{
string filename() const
{
return "CLA1";
}
};
void test_srand()
{
for (int i = 0; i < 5; i++)
{
cout << "rand() = " << rand() % 100 << endl;
}
cout << "-----------------------" << endl;
srand(time(0));
for (int i = 0; i < 5; i++)
{
cout << "rand() = " << rand() % 100 << endl;
}
}
class TEST
{
public:
TEST()
{
cout << "TEST()" << endl;
t_i = t_j = t_k = 0;
}
explicit TEST(int value)
{
cout << "TEST(int value)" << endl;
t_i = t_j = t_k = value;
}
void show()
{
cout << "i = " << t_i << endl;
cout << "j = " << t_j << endl;
cout << "k = " << t_k << endl;
}
operator int() const;
operator double() const;
private:
int t_i;
int t_j;
int t_k;
};
TEST::operator int() const
{
return 512;
}
TEST::operator double() const
{
return 3.14;
}
int main()
{
Time t1;
cout << t1 << "main()"; //测试二元操作数 << 和友元函数重载
cout << '\n';
// VEC::test1(); //测试命名空间 namespace作用域
// LIST::test1();
cout << "---------------------------------" << endl;
// CLA1 cla1;
// CLA2 cla2;
//
// TESTFILENAME::save<CLA1>(cla1);
// TESTFILENAME::save<CLA2>(cla2); //函数模板 template typename
// test_srand(); //测试随机数种子
// int * p = 10;
// int *p1 = (int*)10;
//
// cout << "p1 = " << p1 << endl; //指针非法赋值
// TEST t;
// t.show();
// t = 2; //explicit 不能使用隐式转换
// t.show(); //拷贝构造
// int i = t; //转换函数
// cout << "i = " << i << endl;
// double d = t;
// cout << "d = " << d << endl;
}