共享数据保护

共享数据的保护

常对象

常对象是一个特别的对像:它的数据成员值在整个对象的生存期间内不能被改变。即常对象必须进行初始化,而且不能被更新

class A
{
	public:
    A(int x,int y):x(i),y(j){}

    private:
	int x,y;

}
const A a(3,4);

这样的一个用const修饰的对象是一个常对象在定义常对象时需要对它赋初值,并且该常对象的初值并不会随程序的运行而发生改变

用const修饰的类成员

常成员函数

声明方式:
类型说明符 函数名(参数表) const;
在函数重载时加const的常成员函数与常规的函数相同命名时构成有效重载函数如:

void print();
void print() const;

#include<iostream>
using namespace std;

class R{

public:
	R(int r1, int r2) :r1(r1), r2(r2){ };
	void print();
	void print() const;
private:
	int r1, r2;
};
void R::print(){

	cout << r1 << ":" << r2 << endl;
}

void R::print() const{

	cout << r1 << ":" << r2 << endl;
}
int main()
{
	R a(5, 4);
	a.print();
	const R b(8, 10);
	b.print();
	return 0;

}

常对象只能调用它的常成员函数,而不能调用其他成员函数(c++语法机制上的对常对象的保护)
无论是否通过常对象调用常成员函数,在调用常成员函数期间目标对象都被视为常对象,因而常成员函数无法对目标对象的数据成员进行修改

常数据成员

常数据成员一旦声明并初始化,任何函数都将无法对该成员赋值,构造函数对该数据成员进行初始化,就只能通过初始化列表。

#include<iostream>
using namespace std;

class A{

public:
	A(int i);
	void print() ;
private:
	const int a;
	static const int b;
};
const int A::b = 10;//给静态常数据成员赋值

A::A(int i) :a(i){} // 构造函数

void A::print(){

	cout << a << ":" << b<< endl;
}

int main()
{
	A a1(100),a2(0);//给常数据成员赋值
	a1.print();
	a2.print();
	
	return 0;

}

常引用

如果在声明引用时用const修饰,被声明的引用就是常引用,常引用所引用的对象不能被更新
若用常引用做形参,便不会意外地发生对实参的更改。
常引用的声明:
const 类型说明符 &引用名;

#include<iostream>
using namespace std;

class Point{

public:
	Point(int x = 0, int y = 0) :x(x), y(y){}
	int getx(){ return x; }
	int gety(){ return y; }
	friend  float dist(const Point &p1, const Point &p2);//常对象引用
private:
	int x, y;
};
//常对象引用作形参
float dist(const Point &p1, const Point &p2){
	double x = p1.x - p2.x;
	double y = p1.y - p2.y;

	return static_cast<float>(sqrt(x*x + y*y));

}

int main()
{
	const Point myp1(1, 1), myp2(4, 5);
	cout << "The distance is:" << endl;
	cout << dist(myp1, myp2) << endl;

	return 0;

}

对于在函数中无需改变其值的参数,不宜使用普通方式传值,因为那会使得对象无法被传入,采用值传递或常引用的方式可以避免这一问题;复制构造函数的参数传递一般也采用常引用传递。

posted @ 2019-09-29 17:33  znlovewxl  阅读(183)  评论(0编辑  收藏  举报