然崽的C++学习笔记

VS2012 下载地址:

链接:https://pan.baidu.com/s/171tyRhDRY0Y2Wi0CsvV5kQ 
提取码:zcnz 
 

VS2012 有效注册密钥

Microsoft Visual Studio Ultimate 2012 旗舰版 有效注册密钥: YKCW6-BPFPF-BT8C9-7DCTH-QXGWC  ;

具体步骤为:帮助-->注册产品-->输入密钥-->下一步   激活完毕。

 

目录


 

C++练习  I/O流

C++练习 实例化一个坐标对象

C++练习 内存管理

C++练习  内存管理

C++练习 使用函数的重载完成返回最大值

 C++练习 rand 生成1-4随机数

C++的函数参数默认值、函数重载、内联函数特性

C++练习 使用const关键字定义整型变量count,并定义指针p引用变量count

C++的const关键字与引用类型结合注意事项

C++的引用

1.简单变量的引用 

2.结构体变量的引用

3.指针类型的引用

C++ 类外定义练习

C++ 初始string

C++ 浅拷贝练习

C++ 继承与派生

C++ isa 

C++ this指针练习

C++ 对象指针练习

C++ const 与默认构造函数

C++ 构造函数练习

C++ 封装练习

C++ 封装的好处

 


C++练习  I/O流

练习:

1.提示用户输入两个整数,该整数分别以8进制、十进制、十六进制打印

2.要求用户输入布尔(0/1),以布尔方式打印在频幕上

#include<iostream>
#include<stdlib.h>
using namespace std;


int main()
{
    cout << "请输入一个整数:" << endl;
    int x = 0;
    cin >> x;
    cout << "8进制:"<< oct << x << endl; 
    cout << "16进制:"<< hex << x << endl; 
    cout << "10进制:" << dec << x << endl;

    cout << "请输入一个布尔值(0/1)" << endl;
    bool y = false;
    cin >> y;
    cout << boolalpha << y << endl;

    system("pause");
    return 0;

}

运行结果:

 

 

C++练习 实例化一个坐标对象

要求: 

1.从类名要看出类的功能

2.类的花括号后不要忘了;号

3.如果用堆申请内存,申请完记得验证是否申请成功,用判断语句判断指针p是否指向空,用完要记得释放内存,避免内存泄漏

#include <iostream>
#include <stdlib.h>
 
using namespace std;
 
class coordinate
{
public:
	int x;
	int y;
	void printxy()
	{
		cout << "(" << x << "," << y << ")" << endl;
 
 
	}
 
 
};
 
 
int main()
{
	cout << "从栈中实例化:" << endl;
	coordinate coor;  //从栈中实例化
	coor.x = 5;
	coor.y = 6;
	coor.printxy();
 
 
 
	cout << "从堆中实例化:" << endl;
	coordinate *p = new coordinate();
	if (NULL == p)
	{
		printf("new failure!");
 
	}                           //如果内存分配失败,打印错误信息
	
	p->x = 4;
	p->y = 5;
	p->printxy();
 
	delete p;                   //用完记得释放内存
	p = NULL;
 
	system("pause");
 
}

 

 

 

C++练习 内存管理

要求:在堆中申请100个char类型的内存,拷贝Hello imooc字符串到分配的堆中的内存中,打印字符串,最后释放内存。

#include <string.h>
#include <iostream>
using namespace std;
int main(void)
{
    //在堆中申请100个char类型的内存
    char *str = new char[100];
    //拷贝Hello C++字符串到分配的堆中的内存中
	strcpy(str, "Hello imooc");
    //打印字符串
    cout<<"str="<<str<<endl;
    //释放内存
delete []str;
str=NULL;
 
	return 0;
}

 

 

 

C++练习  内存管理

内存的本质是什么?            资源

谁掌管内存资源?                 操作系统

我们能做什么?                   申请/归还------------------------->内存管理!

 

申请内存 : new

释放内存:delete  

PS这两个都是运算符,而不是函数。

#include<stdlib.h>
#include <iostream>
using namespace std;
 
 
 
int main()
{
	int *p = new int[10];
	if (NULL == p)
	{
		system("pause");
		return 0;
 
	}
	p[0] = 10;
	p[1] = 20;
	delete []p; //此时已经释放内存
	p = NULL;   //p为空指针
 
	cout << p[0] << endl; //报错,空间已经释放,这不存在
 
 
 
	
	system("pause");
	return 0;
 
}
 

运行结果:

 

 

 

C++练习 使用函数的重载完成返回最大值

要求:使用函数的重载完成返回最大值的方法。

现在有一个数组,定义一个方法getMax(),利用函数的重载,分别实现:

1、随意取出数组中的两个元素,传到方法getMax()中,可以返回较大的一个元素。

2、将整个数组传到方法getMax()中,可以返回数组中最大的一个元素。

#include<stdlib.h>
#include <iostream>
#include <time.h>
using namespace std;
 
 
void getMax(int a, int b)
{
    if (a > b)
        cout << "The max of 2 numeber=" << a << endl;
    else
        cout << "The max of 2 numebe="<< b << endl;
 
}
 
void getMax(int  *p)                    //用指针把数组传入
    {
 
    int i,temp;
    temp = *p;
 
    for (i = 1; i <= 4; i++) 
    {
        if (temp < (*(p + i)))
            temp = *(p + i);
    }
    cout << "The max of arry =" << temp << endl;
    }
 
 
int main()
{
    int i, j;
    int arry[] = { 6,7,5,2,3 };
    srand(time(0));         //srand()初始化随机数种子在stdlib.h里,time()在time.h里
    j = rand() % 4 + 1;       //获得1-4的随机数,原型在stdlib.h里,要获得1-n就 %n
    i = j -1;                 //因为j最小为1,减1为0,arry[0]是存在的
 
    cout << "arry[" << j << "]" << "=" << arry[j] << endl;
    cout << "arry[" << i << "]" << "=" << arry[i] << endl;
 
    getMax(arry[j], arry[i]);
    getMax(arry);
 
    system("pause");
    return 0;
 
 
}

运行结果:

 

 

 

 C++练习 rand 生成1-4随机数

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
    int  j;
    srand(time(0));         //srand()初始化随机数种子在stdlib.h里,time()在time.h里
    j = rand() % 4 + 1;       //获得1-5的随机数,原型在stdlib.h里
    printf("%d\n", j);

    system("pause");
    return 0;
}

 

 

 

C++的函数参数默认值、函数重载、内联函数特性

1.函数参数默认值:

注意:有默参数值的必须写在参数最右端。

声明时可加默认值,定义时不建议写默认值(有些编译器能通过,有些不能)

2.函数重载 :

在相同作用域内,同名函数,参数个数和参数类型不同,构成函数重载

#include<stdlib.h>
#include <iostream>
 
using namespace std;
 
void fun(int i=30, int j=20, int k=10)
{
	cout << i << "," << j << "," << k << endl;
 
}
 
int main()
{
 
	fun(4);
	fun(4, 5);
	fun(4,5,6);
  system("pause");
  return 0;
 
 
}
 

 结论:无实参则使用默认值

  

#include<stdlib.h>
#include <iostream>
 
using namespace std;
 
/*第一个fun函数*/
void fun(int i=30, int j=20, int k=10)   // 系统会化成 fun_int_int_int
{
	cout << i << "," << j << "," << k << endl;
 
}
 
/*第二个fun函数*/
void fun(double i, double j)            // 系统会化成 fun_double_double
{
	cout << i << "," << j << "," << endl;
}
 
 
int main()
{
 
	fun(4);                  //fun_int_int_int类型的,调用第一个函数
	fun(1.1, 2.2);           //fun_double_double类型的,调用第二个函数
	fun(1.1,2);           //fun_double_int类型的,不存在这个重载函数fun,报错
 
    system("pause");
    return 0;
 
 
}

运行结果:

 

如果我fun(1,2.2)一个不存在的重载类型呢?

显然这是一个fun_int_double类型的,但是没有这样的重载函数定义,编译器会报错,无法识别是哪种

运行结果:

1>------ 已启动生成: 项目: love, 配置: Debug Win32 ------
1>love.cpp
1>e:\c++\my c++\love\love\love.cpp(20): error C2666: “fun”: 2 个重载有相似的转换
1>e:\c++\my c++\love\love\love.cpp(12): note: 可能是“void fun(double,double)”
1>e:\c++\my c++\love\love\love.cpp(6): note: 或    “void fun(int,int,int)”
1>e:\c++\my c++\love\love\love.cpp(20): note: 尝试匹配参数列表“(double, int)”时
1>已完成生成项目“love.vcxproj”的操作 - 失败。
========== 生成: 成功 0 个,失败 1 个,最新 0 个,跳过 0 个 ==========

 

 

 

C++练习 使用const关键字定义整型变量count,并定义指针p引用变量count

要求:

使用const关键字定义整型变量count,并定义指针p引用变量count。利用for循环打印count次Hello imooc

#include<stdlib.h>
#include <iostream>
 
using namespace std;
 
 
 
int main()
{
	
	const int count = 5;
	int i;
	const int *p = &count;
	for (i = 1; i <= count; i++)
	{
		cout << "Hello imooc" << endl;
 
	}
	
 
  system("pause");
  return 0;
 
 
}
 

const int count = 3;
int *p =  &count;为什么这样不行?

count定义的是const类型的,说明count是不能改变值的,而下面又定义了一个可变的*p指向了count,岂不是接下来就可以写*p=?来改变count的值了吗?所以编译会报错。指向常量的指针也必须定义成const int *p。

 

 

 

C++的const关键字与引用类型结合注意事项

例1:

int x = 3;                          //x是变量

int const &y = x;            //y是x的引用,但const修饰了 &y

1,x的值可以修改

2,引用y的值不可以修改

(1)尝试修改x:

#include<stdlib.h>
#include<iostream>
 
using namespace std;
 
 
int main()
{
	int x = 3;
	int const &y = x;
	x = 9;
 
 
	cout << "x=" << x << endl;
	cout << "y=" << y << endl;
 
 
 
	system("pause");
	return 0;
 
}

运行结果:

(2)尝试修改y

#include<stdlib.h>
#include<iostream>
 
using namespace std;
 
 
int main()
{
	int x = 3;
	int const &y = x; //const修饰y
	y= 9;             //报错
 
 
	cout << "x=" << x << endl;
	cout << "y=" << y << endl;
 
 
 
	system("pause");
	return 0;
 
}

运行结果:编译不通过

1>------ 已启动生成: 项目: ConsoleApplication1, 配置: Debug Win32 ------
1>luoyiran.cpp
1>e:\c++\my c++\consoleapplication1\consoleapplication1\luoyiran.cpp(11): error C3892: “y”: 不能给常量赋值
1>已完成生成项目“ConsoleApplication1.vcxproj”的操作 - 失败。
========== 生成: 成功 0 个,失败 1 个,最新 0 个,跳过 0 个 ==========

 

例2:

int x = 3;               
int & const y = x;

值得注意的是,这种情况居然可以修改y值

#include<stdlib.h>
#include<iostream>
 
using namespace std;
 
 
int main()
{
	int x = 3;
	int& const y = x;
	y= 9;
 
 
	cout << "x=" << x << endl;
	cout << "y=" << y << endl;
 
 
 
	system("pause");
	return 0;
 
}

运行结果:

例3:

void fun(const  int &a,const  int &b)   //传入的值不可更改

 

1)传入的参数没有const修饰:

#include<stdlib.h>
#include <iostream>
 
using namespace std;
 
 
void fun(int &a, int &b)        //传入的参数没有const修饰
{
	a = 6;
	b = 4;
 
 
 }
 
int main()
{
	int x = 5;
	int y = 6;
 
	fun(x, y);          //调用函数
 
	cout << "x=" << x << endl;
	cout << "y=" << y << endl;
 
  system("pause");
  return 0;
 
 
}
 

运行结果:可以发现,x、y的值改变了。

(2)传入的参数用const修饰:

#include<stdlib.h>
#include <iostream>
 
using namespace std;
 
 
void fun(const int &a,const int &b) // 传入的参数用const修饰
{
	a = 6;
	b = 4;
 
 
 }
 
int main()
{
	int x = 5;
	int y = 6;
 
	fun(x, y);                          //调用函数
 
	cout << "x=" << x << endl;
	cout << "y=" << y << endl;
 
  system("pause");
  return 0;
 
 
}
 

运行结果:编译报错。

1>------ 已启动生成: 项目: love, 配置: Debug Win32 ------
1>love.cpp
1>e:\c++\my c++\love\love\love.cpp(9): error C3892: “a”: 不能给常量赋值
1>e:\c++\my c++\love\love\love.cpp(10): error C3892: “b”: 不能给常量赋值
1>已完成生成项目“love.vcxproj”的操作 - 失败。
========== 生成: 成功 0 个,失败 1 个,最新 0 个,跳过 0 个 ==========

 

 

 

C++的引用

1.简单变量的引用 

#include<stdlib.h>
#include<iostream>
 
using namespace std;
 
int main()
{
	int a = 3;
	int &b = a;
	b = 20;
	cout << a << endl;
 
 
 
}

2.结构体变量的引用

#include<stdlib.h>
#include<iostream>
 
using namespace std;
 
int main()
{
	
	typedef struct
	{
		int x;
		int y;
 
	}code;
 
	code a;
	code &b = a;
	b.x = 10;
	b.y = 20;
	cout << a.x <<endl<< a.y << endl;
 
	system("pause");
	return 0;
 
}

3.指针类型的引用

要求:定义一个teacher类,要求分别用同文件类外定义和分文件类外定义的方式完成

要求如下:数据成员:名字 年龄 

                  成员函数:数据成员的封装函数setxx()/  getxx() /   授课teach()

/*同文件类外定义*/
 
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
 
/*类内声明*/
 
class Teacher
{
public:
	void setName(string name);   //传进一个参数
	string getName();            //返回一个参数
 
	void setAge(int age);
	int getAge();
 
	void teach();
 
private:
	string myName;
	int myAge;
 
 
 
};
 
 
/*类外定义*/
 
void Teacher::setName(string name)
{
	myName = name;
}
string Teacher::getName()
{
	return myName;
}
void Teacher::setAge(int age)
 
{
		myAge = age;
}
int Teacher::getAge()
{
	
	return myAge;
	
}
 
void Teacher::teach()
{
	cout << "现在开始上课..." << endl;
 
}
int main(void)
 
	{
	 Teacher t;
	t.setName("罗依然");
	t.setAge(21);
	
	cout << t.getName()<< endl<<t.getAge() <<endl;
	t.teach();
	system("pause");
	return 0;
	}

C++ 类外定义练习

要求:定义一个teacher类,要求分别用同文件类外定义和分文件类外定义的方式完成

要求如下:数据成员:名字 年龄 

                  成员函数:数据成员的封装函数setxx()/  getxx() /   授课teach()

/*同文件类外定义*/
 
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
 
/*类内声明*/
 
class Teacher
{
public:
	void setName(string name);   //传进一个参数
	string getName();            //返回一个参数
 
	void setAge(int age);
	int getAge();
 
	void teach();
 
private:
	string myName;
	int myAge;
 
 
 
};
 
 
/*类外定义*/
 
void Teacher::setName(string name)
{
	myName = name;
}
string Teacher::getName()
{
	return myName;
}
void Teacher::setAge(int age)
 
{
		myAge = age;
}
int Teacher::getAge()
{
	
	return myAge;
	
}
 
void Teacher::teach()
{
	cout << "现在开始上课..." << endl;
 
}
int main(void)
 
	{
	 Teacher t;
	t.setName("罗依然");
	t.setAge(21);
	
	cout << t.getName()<< endl<<t.getAge() <<endl;
	t.teach();
	system("pause");
	return 0;
	}

结果: 

 

C++ 初始string

要求:

1.提示用户输入姓名

2.接受用户的输入

3.然后向用户问好,helloxxx

4.告诉用户名字的长度

5.告诉用户名字的首字母是什么

6.如果用户直接输入回车,那么告诉用户的输入为空

7.如果用户输入的是imooc,告诉用户的角色是个管理员

#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
 
 
int main()
{
	string name; //使得name 获得一个空串
	cout << "请输入您的名字:" << endl;
	getline(cin, name);
	if (name.empty())
	{
		cout << "输入为空" << endl;
		return 0;
 
	}
 
	if (name == "imooc")
		{
			cout << "您是管理员" << endl;
 
		}
	string c = "hello," + name;
	cout << c << endl;
	cout << "your name length:" <<name.size() << endl;
	cout << "your name first letter is:"<<name[0] << endl;
 
 
 
 
	system("pause");
 
}

运行结果:

 

 

 

C++ 浅拷贝练习

#include <iostream>
#include <stdlib.h>
#include <string>
 
using namespace std;
 
class Array
{
public:
	Array()    //原构造函数
	{
		cout << "Array()" << endl;
		m_icount = 5; 
        m_ptr= new int[m_icount]; //在堆中实例化对象,如销毁对象时需要调用析构函数
		
	}
 
	Array(const Array&arr)   //拷贝构造函数
	{
		cout << "array&" << endl;
		m_icount = arr.m_icount;
		m_ptr = new int[m_icount];
		for (int i = 0; i < m_icount; i++)
		{
			m_ptr[i] = arr.m_ptr[i];
 
		}
	}
 
		~Array()          //析构函数
	
		{
			cout << "~array()" << endl;
		}
		void set_count(int count)
		{
			m_icount = count;
 
		}
		int get_count()
		{
			return m_icount;
		}
 
	private:
	int m_icount;
	int *m_ptr;
	};
 
	int main(void)
	{
		Array arr1;    //实例化对象arr1
		arr1.set_count(5);//给对象的成员函数赋值,此时调用构造函数Array()
		cout << arr1.get_count() << endl;//打印另一个成员函数的值,看是否数据成员m_count被改变
 
		Array arr2 = arr1;//用对象arr1实例化对象arr2,此时调用拷贝构造函数Array(const Array&arr)此时的arr变量就是arr1
		cout << arr2.get_count() << endl;
		system("pause");
 
 
	}

运行结果:可以看出,实例化对象arr1时,系统调用了构造函数Array(),用arr2实例化对象arr1时,调用了拷贝构造函数Array(const Array&arr),此时变量arr就是arr1!

当我们按任意键结束时,要调用两次析构函数销毁对象arr1和对象arr2!

 

 

 

C++ 继承与派生

 

#include <iostream>
#include  <stdlib.h>
using namespace std;
 
class person
{
public:
	person();
	~person();
	void eat() { cout << "eat haha" << endl; }
	string m_Name;
	int m_Age;
 
};
person::person()
{
	cout << "调用了构造函数person()" << endl;
}
person::~person()
{
	cout << "调用了析构函数~person()" << endl;
}
 
class worker:public person
{
public:
	worker() 
	{
		cout << "调用了worker()" << endl;
	}
	~worker() 
	{
		cout << "调用了析构函数worker()" << endl;
	}
 
	void work()
	{
		cout << "work beging!" << endl;
	}
	
};
 
 
 
int main()
{
	worker *p=new worker();//实例化子类对象
	p->m_Name = "luoyiran";
	p->m_Age = 21;
	p->eat();//访问person(父类)的成员函数
	p->work();//访问自己(子类)的成员函数
 
	delete p;
	p = NULL;
}

运行结果:

总结:

子类可以访问父类的公有数据成员

先调用父类的构造函数再调用子类的构造函数,销毁对象时,先调用子类的构造函数,再调用父类的构造函数,顺序刚好相反。

 

 

 

C++ isa 

#include <iostream>
#include <string>
#include <stdlib.h>
 
using namespace std;
class Person
{
public:
	Person(string name = "jim")
	{
		m_name = name;
		cout << "调用了Person()" << endl;
	}
	~Person()
	{
		cout << "调用了析构函数~Person()" << endl;
	}
	void play()
	{
		cout << "person--play" << endl;
		cout << m_name << endl;
 
	}
protected:
	string m_name;
 
};
class Soldier :public Person
{
public:
 
	Soldier(string name = "james", int age = 20)
	{
		m_name = name;
		m_age = age;
		cout << "调用了soldier()" << endl;
 
	}
	~Soldier()
	{
		cout << "调用了析构函数~Soldier()" << endl;
	}
	void work()
	{
		cout << m_name << endl;
		cout << m_age << endl;
		cout << "soldier--work()" << endl;
 
	}
protected:
	int m_age;
};
 
int main(void)
{
Person *P1=new Soldier; //用person(父类)指针指向从堆中分配来的soldier(子类)对象
P1->play();
delete P1;//销毁父类对象指针P1
P1 = NULL;
	
 
 
	system("pause");
	return 0;
}

观察现象:

解决方法:

在子类和父类的析构函数之前加上virtual

运行结果:

 

 

 

 

C++ this指针练习

计算机无法判断是参数赋值给数据成员还是数据成员赋值给参数,所以我们需要一种this指针,this指针是指向对象数据成员的

 

using namespace std;
class Array
{
 
public:
	Array(int len)
	{
		cout << "调用了构造函数" << endl;
		this->len = len;
 
	}
	~Array() 
	{
		cout << "调用了析构函数" << endl;
	}
	void setLen(int len)
	{
		this->len = len;
 
	}
	int getLen()
	{
		return len;
	}
	void printinfo()
	{
 
	}
    
private:
	int len;       //<=>    this->len   
 
	
};
 
int main(void)
{
	Array arr1(10);
	cout << arr1.getLen() << endl;
		system("pause");
	return 0;
}

 

 

 

C++ 对象指针练习

#include <iostream>
#include  <stdlib.h>
using namespace std;
class Coordinate
{
 
public:
	Coordinate(int x, int y)
	{
		// 设置X,Y的坐标
		m_iX = x;
		m_iY = y;
 
	}
public:
	int m_iX;
	int m_iY;
};
 
int main(void)
{
	// 在堆上创建对象指针
	Coordinate *p = new Coordinate(3,5);
	// 打印坐标
	cout << p->m_iX << "," << p->m_iY << endl;
	// 销毁对象指针
	delete p;
	p = NULL;
	return 0;
	system("pause");
}

运行结果:

 

 

 

C++ const 与默认构造函数

#include <iostream>
#include <stdlib.h>
#include <string>
 
using namespace std;
 
class Teacher
{
public:
	/*构造函数与类名相同*/
 
	Teacher(string name = "jim", int age = 10, int max=100);//函数声明,并赋予默认值
	
 
	void setName(string name);   //传进一个参数
	string getName();            //返回一个参数
 
	void setAge(int age);
	int getAge();
	
	void setMax(int max);
	int getMax();
	
	
 
 
private:
	string myName;
	int myAge;
	const int myAge_max;
 
 
};
 
/*类外定义*/
Teacher::Teacher(string name, int age, int max):myName(name), myAge(age),myAge_max(max)
{
	
	cout << "调用的是Teacher(string name, int age)" << endl;
}       //给初始化列表赋值,传参,会改变函数声明中的默认值
 
void Teacher::setName(string name)
{
	myName = name;
}
string Teacher::getName()
{
	return myName;
}
 
void Teacher::setAge(int age)
 
{
	myAge = age;
}
int Teacher::getAge()
{
 
	return myAge;
 
}
 
 
int Teacher::getMax()
{
	return myAge_max;
}
 
int main(void)
 
{
	Teacher t1("MERRY",12,200);
   
	
	cout << t1.getName()<<"  "<<t1.getAge() <<"  "<<t1.getMax()<< endl;
 
	
		system("pause");
	return 0;
}

 

 

 

C++ 构造函数练习

 构造函数注意事项:

1.构造函数在对象实例化时,被自动调用

2.构造函数要与类同名

3.构造函数无返回值(void都不用写哦)

4.实例化对象时仅用到一个构造函数

5.当用户没有定义构造函数时,编译器自动生成一个构造函数

6.构造函数可以有多个重载形式

 

练习:Teacher类:

 *          自定义无参数构造函数;

 *          自定义有参数构造函数;

数据:

 *         名字;

 *         年龄;

成员函数:

*          数据成员的封装函数

 

#include <iostream>
#include <stdlib.h>
#include <string>
 
using namespace std;
 
class Teacher
{
public:
	/*构造函数与类名相同*/
	Teacher()
		{
			myName = "jim";
			myAge = 5;
			cout << "调用的是Teacher()" << endl; //为了区分调用哪个函数,所以要打印
 
		}
	Teacher(string name, int age)
	{
		myName = name;
		myAge = age;
		cout << "调用的是Teacher(string name, int age)" << endl;
	}
 
	void setName(string name);   //传进一个参数
	string getName();            //返回一个参数
 
	void setAge(int age);
	int getAge();
 
	void teach();
 
 
private:
	string myName;
	int myAge;
 
 
};
 
/*类外定义*/
 
void Teacher::setName(string name)
{
	myName = name;
}
string Teacher::getName()
{
	return myName;
}
void Teacher::setAge(int age)
 
{
	myAge = age;
}
int Teacher::getAge()
{
 
	return myAge;
 
}
 
 
int main(void)
 
{
	Teacher t1;
    Teacher t2("merry",15);
	cout << t1.getName()<<"  "<<t1.getAge() << endl;
	cout << t2.getName() <<"  "<<t2.getAge()<< endl;
	
		system("pause");
	return 0;
}

 

 

 

C++ 封装练习

#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
 
 
class Student
{
public:
	void setName(string name)
	{
		myName =name;  //可读可写,外界可设置名字
	}
	string getName()
	{
		return myName;
	}
	void setGender(string gender)
	{
		myGender = gender;
	}
	string getGender()
	{
		return myGender;
	}
	void setScore(int score)
	{
		myScore = score;
	}
	int getScore()
	{
		return myScore;
	}
 
 
private:
	string myName;
	string myGender;
	int myScore = 100;//只读,私有成员,外界不可设置分数
};
 
int main(void)
{
	Student stu;
	stu.setName("ZHANGSHAN");
	stu.setGender("女");
	
	cout << stu.getName() << endl;
	cout << stu.getGender() << endl;
	cout << stu.getScore() << endl;
 
		system("pause");
	return 0;
}

运行结果:

如果非要设置score,会报错

 

int main(void)
{
	Student stu;
	stu.setName("ZHANGSHAN");
	stu.setGender("女");
	stu.setScore(100); //设置私有成员
	
	cout << stu.getName() << endl;
	cout << stu.getGender() << endl;
	cout << stu.getScore() << endl;
 
		system("pause");
	return 0;
}

单元巩固要求:

定义一个Student类,包含名字一个数据成员,使用get和set函数封装名字这个数据成员。在main函数中通过new实例化对象,并打印其相关函数。

 

#include <iostream>
#include <string>
using namespace std;
 
/**
  * 定义类:Student
  * 数据成员:m_strName
  * 数据成员的封装函数:setName()、getName()
  */
class Student
{
public:
    // 定义数据成员封装函数setName()
    void setName(string name)
    {
        m_strName=name;
    }
    
    // 定义数据成员封装函数getName()
    string getName()
    {
        return m_strName;
        
    }
    
    
//定义Student类私有数据成员m_strName
private:
string m_strName;
};
 
int main()
{
    // 使用new关键字,实例化对象
	Student *str = new Student();
    // 设置对象的数据成员
	str->setName("慕课网");
    // 使用cout打印对象str的数据成员
    cout<<str->getName()<<endl;
 
    // 将对象str的内存释放,并将其置空
	delete str;
    str=NULL;
	return 0;
}

 

 

 

C++ 封装的好处

封装的好处:

1.可以让目的值只能读取不能设置;

2.不能更改;

3.限制条件,避免成员函数、成员数据赋值不符合现实逻辑;

如:

#include <iostream>
using namespace std;
 
class Student
{
public:
{
    int getWheelCount()
    {
        return m_iWheelCount;
 
    }
private:
    int m_iWheelCount;  //只读属性
 
}

 

目 录 前 言6 第1 章 文件结构 1.1 版权和版本的声明. 1.2 头文件的结构. 1.3 定义文件的结构. 1.4 头文件的作用. 1.5 目录结构. 第2 章 程序的版式 2.1 空行. 2.2 代码行. 2.3 代码行内的空格. 2.4 对齐. 2.5 长行拆分. 2.6 修饰符的位置. 2.7 注释. 2.8 类的版式. 第3 章 命名规则 3.1 共性规则. 3.2 简单的WINDOWS 应用程序命名规则. 3.3 简单的UNIX 应用程序命名规则 第4 章 表达式和基本语句 4.1 运算符的优先级. 4.2 复合表达式. 4.3 IF 语句 4.4 循环语句的效率. 4.5 FOR 语句的循环控制变量. 4.6 SWITCH 语句. 4.7 GOTO 语句. 第5 章 常量 5.1 为什么需要常量. 5.2 CONST 与 #DEFINE 的比较. 5.3 常量定义规则. 5.4 类中的常量. 第6 章 函数设计 高质量C++/C 编程指南,v 1.0 2001 Page 4 of 101 6.1 参数的规则. 6.2 返回值的规则. 6.3 函数内部实现的规则. 6.4 其它建议. 6.5 使用断言. 6.6 引用与指针的比较. 第7 章 内存管理 7.1 内存分配方式 7.2 常见的内存错误及其对策 7.3 指针与数组的对比 7.4 指针参数是如何传递内存的? 7.5 FREE 和DELETE 把指针怎么啦? 7.6 动态内存会被自动释放吗?. 7.7 杜绝“野指针”. 7.8 有了MALLOC/FREE 为什么还要NEW/DELETE ?. 7.9 内存耗尽怎么办?. 7.10 MALLOC/FREE 的使用要点 7.11 NEW/DELETE 的使用要点. 7.12 一些心得体会 第8 章 C++函数的高级特性 8.1 函数重载的概念. 8.2 成员函数的重载、覆盖与隐藏. 8.3 参数的缺省值. 8.4 运算符重载. 8.5 函数内联. 8.6 一些心得体会. 第9 章 类的构造函数、析构函数与赋值函数 9.1 构造函数与析构函数的起源. 9.2 构造函数的初始化表. 9.3 构造和析构的次序. 9.4 示例:类STRING 的构造函数与析构函数 9.5 不要轻视拷贝构造函数与赋值函数. 9.6 示例:类STRING 的拷贝构造函数与赋值函数 9.7 偷懒的办法处理拷贝构造函数与赋值函数. 9.8 如何在派生类中实现类的基本函数. 9.9 一些心得体会. 第10 章 类的继承与组合. 高质量C++/C 编程指南,v 1.0 2001 Page 5 of 101 10.1 继承 10.2 组合 第11 章 其它编程经验. 11.1 使用CONST 提高函数的健壮性 11.2 提高程序的效率 11.3 一些有益的建议 参考文献 附录A :C++/C 代码审查表. 附录B :C++/C 试题. 附录C :C++/C 试题的答案与评分标准.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值