C++ [ 共享数据保护 ]
2011-09-26 09:31
441 查看
1、常引用:所引用的对象不能更新
const 类型说明符 &引用名;
#include <iostream.h>
void display(const double& r);
int main(void){
double d(9.5);
display(d);
return 0;
}
void display(const double& r){
/*
r = 10;
error C2166: l-value specifies const object
*/
//常饮用做形参,函数中不能更新r所引用的对象
cout<<r<<endl;
}
2、常对象:必须进行初始化,而且不能被更新
类名 const 对象名;
#include <stdlib.h>
using namespace std;
class A{
public:
A(int i, int j){x=i;y=j;}
void setX(int x){x=x;}
void setX(int x) const {x=x;}
private:
int x,y;
};
int main(int argc, char *argv[])
{
int const n=10;
//a是常对象,不能被更新
A const a(3,4);
/*
a.setX(5);
'const A' as 'this argument of 'void A::setX(int)' discards qualifiers
*/
system("PAUSE");
return 0;
}
3、常成员函数
类型说明符 函数名(参数表) const;
常对象可以调用常成员函数
4、常数据成员
构造函数对数据成员进行初始化;静态常数据成员在类外说明和初始化
#include <iostream>
#include <stdlib.h>
using namespace std;
class A{
public:
A(int i);
void print();
const int& r;
private:
const int a;
static const int b;
};
const int A::b=10;
A::A(int i):a(i),r(a){
}
void A::print(){
cout<<a<<":"<<b<<":"<<r<<endl;
}
int main(int argc, char *argv[])
{
A a1(100);
a1.print();
system("PAUSE");
return 0;
}
const 类型说明符 &引用名;
#include <iostream.h>
void display(const double& r);
int main(void){
double d(9.5);
display(d);
return 0;
}
void display(const double& r){
/*
r = 10;
error C2166: l-value specifies const object
*/
//常饮用做形参,函数中不能更新r所引用的对象
cout<<r<<endl;
}
2、常对象:必须进行初始化,而且不能被更新
类名 const 对象名;
#include <stdlib.h>
using namespace std;
class A{
public:
A(int i, int j){x=i;y=j;}
void setX(int x){x=x;}
void setX(int x) const {x=x;}
private:
int x,y;
};
int main(int argc, char *argv[])
{
int const n=10;
//a是常对象,不能被更新
A const a(3,4);
/*
a.setX(5);
'const A' as 'this argument of 'void A::setX(int)' discards qualifiers
*/
system("PAUSE");
return 0;
}
3、常成员函数
类型说明符 函数名(参数表) const;
常对象可以调用常成员函数
4、常数据成员
构造函数对数据成员进行初始化;静态常数据成员在类外说明和初始化
#include <iostream>
#include <stdlib.h>
using namespace std;
class A{
public:
A(int i);
void print();
const int& r;
private:
const int a;
static const int b;
};
const int A::b=10;
A::A(int i):a(i),r(a){
}
void A::print(){
cout<<a<<":"<<b<<":"<<r<<endl;
}
int main(int argc, char *argv[])
{
A a1(100);
a1.print();
system("PAUSE");
return 0;
}
相关文章推荐
- 2015级C++第7周项目 友元、共享数据保护、多文件结构
- C++多线程笔记:使用std::lock_guard实现对共享数据的保护
- C++基础知识总结与回顾--5.5共享数据的保护
- C++ 学习之路(7):共享数据的保护
- C++入门笔记(三)数据的共享与保护
- C++并发实战10:保护共享数据的可选机制
- C++中共享数据的保护
- 2015级C++第7周项目 友元、共享数据保护、多文件结构
- 探究在C++程序并发时保护共享数据的问题
- C/C++基础知识总结——数据的共享与保护
- C++数据的共享与保护
- C++共享数据的保护(常对象,常成员,常引用)
- C++:数据的共享与保护
- C/C++基础知识总结——数据的共享与保护
- C++共享数据类型的保护(常类型)
- C++文本查询程序 定义类管理数据 用引用共享数据 不用智能指针 C++Primer练习12.27
- C++文本查询程序 定义类管理数据 用引用共享数据 不用智能指针 C++Primer练习12.27
- c++ 数据共享
- const 数据共享与保护
- C++文本查询程序 定义类管理数据 用引用共享数据 不用智能指针 C++Primer练习12.27