C++PrimerPlus_11 学习笔记

学习内容:

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;
	
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值