C++小记(二)

关键字:类、权限、构造函数、析构函数

类的定义,以及权限的相关知识,用一道经典题来解释:点与圆的位置关系

定义两个类:Circle和Point

//Circle.h
#ifndef _CIRCLE_H
#define _CIRCLE_H

class Circle
{
private:     //成员变量在类中默认私有权限,在结构体中默认公有
	int m_r;
	int x0;
	int y0;
protected:   //保护(用于继承)
public:
	void get_r(int r);
	void get_circle(int px0, int py0);
	void judge(int m, int n);
	
	

};

class Point
{
private:
	int x;
	int y;
public:
	void getPoint(int px, int py);
	int getPointX();
	int getPointY();

};


#endif

在main.c中能对权限做相关测试:

#include "circle.h"
#include "iostream"
#include "windows.h"
using namespace std;

int main()
{
	Circle c1;
	Point p1;
	int r;  //目标圆的半径
	int circle_m, circle_n;  //目标圆的坐标
	int point_m, point_n;
	//c1.m_r;                                    //编译错误,成员变量私有,不能直接访问
	cout << "请输入圆的半径: " << endl;
	cin >> r;
	c1.get_r(r);                          //成员函数公有权限,可通过成员函数访问成员变量
	cout << "请输入圆的坐标: " << endl;
	cin >> circle_m >> circle_n;
	c1.get_circle(circle_m, circle_n);
	cout << "请输入点的坐标: " << endl;
	cin >> point_m >> point_n;
	p1.getPoint(point_m, point_n);

	//system("pause");
	
	c1.judge(p1.getPointX(), p1.getPointY());
	system("pause");
	
	return 0;
}

由以上代码可知,成员变量在类中默认为私有权限,不能直接访问,而成员函数的权限默认为公有,可通过成员函数访问成员变量

附各函数实现方法,仅供参考

                                                  //circle.cpp
#include "iostream"
#include "circle.h"
using namespace std;

void Circle::get_r(int r)                         //注意函数实现的作用域!!!
{
	m_r = r;
}



void Circle::get_circle(int px0,int py0)
{
	 x0 = px0;
	 y0 = py0;
}

void Circle::judge(int m, int n)
{
	int distance = 0;
	distance = (x0 - m)*(x0 - m) + (y0 - n)*(y0 - n);
	if (distance > m_r * m_r)
	{
		cout << "该点在圆外" << endl;
		
	}
	else if (distance = m_r * m_r)
	{
		cout << "该点在圆上" << endl;
		
	}
	else
	{
		cout << "该点在圆内" << endl;
		
	}
}



void Point::getPoint(int px, int py)
{
	x = px;
	y = py;
}


int Point::getPointX()
{
	return x;
}

int Point::getPointY()
{
	return y ;
}

构造函数与析构函数:

构造函数必须与类同名,无返回值,可带参数,在创建对象时自动调用,可完成成员变量赋值,初始化等操作

析构函数也与类名相同,在函数名前面加上符号"~",在对象被释放的时候自动调用,完成各空间的释放,比如堆空间的释放free()

同样的,举例说明:

#include "iostream"
#include "windows.h"
using namespace std;

class Test
{
private:
	int t_x;
	int t_y;
public:
	Test();    //无参构造函数    只有构造函数才能既没有返回值和形参

	Test(int a, int b); //有参构造函数    构造函数可重载
	~Test();
};

Test::Test()
{
	t_x = 1;
	t_y = 2;
	cout << "constructor" << endl;
}

Test::Test(int a, int b)
{
	t_x = a;
	t_y = b;
	cout << "constructor2" << endl;
}

Test::~Test()               //析构函数  
{
	cout << "destructor" << endl;
}

/*void function()
{
	cout << "function on!" << endl;
	Test t2;						//析构函数在对象被释放后自动调用
	cout << "function off!" << endl;
}*/


int main()
{   
	Test t;  // 构造函数在创建对象后自动调用
	Test t1(1, 2);  //有参构造函数的调用
	//function();
	system("pause");
						//析构函数在对象被释放后自动调用
	return 0;
}

另外,编译器默认提供无参的构造函数(函数体为空)和拷贝构造函数(浅拷贝)

所以,拷贝构造函数应当自己写一个深拷贝的拷贝构造函数

猜你喜欢

转载自blog.csdn.net/userkiller/article/details/81165840