1、文件的输入输出:
fstream infile
ofstream outfile;
int income, tax;
infile.open(“FILENAME1”); // open the files
outfile.open(“FILENAME2”);
while ( infile >> income )
{
if ( income << cutoff )
tax = rate1 * income;
else
tax = rate2 * income;
outfile << "Income = " << income
<< " greenbacks\n"
<< "Tax = " << tax
<< " greenbacks\n";
}
infile.close();
outfile.close();//close the file s
2、casts
//static_cast
average = (float) hits / (float) at_bats;
average = static_cast<float>(hits) / static_cast<float>(at_bats);
const_cast
#include <iostream>
using namespace std;
int main()
{
const int i = 100;
const int *p = &i;
int *q = const_cast<int*>(p);
int j = i;
(*q)++;
cout << i << endl << j <<
endl << *p << endl << *q <<endl;
return 0;
}
output:
100
100
101
101
利用const_cast和引用可改变const的值
reinterpret_cast
Usedto convert a pointer of one type to a pointer of
anothertype.
Implementationdependent, must be used with
caution.
dynamic_cast
Usedfor casting across or within inheritance.
Const
1、const对象必须初始化:
constint a = 1;//right
constint k;//wrong
2、const对象赋值:
constint cc = 1;
inti = cc;
consti = cc;
等号左边无所谓const。
3、const的引用:
inti = 42;
constint &r1 = i;
constint &r2 = 42;
constint &r3 = r1 * 2;
int&r4 = ri;//wrong:试图让一个非常量引用指向一个常量对象
(*)以下4、5、6、均转载自:http://blog.csdn.net/my_mao/article/details/22872149
4、const修饰函数
用const 修饰成员函数,使函数无法改变数据成员
int get_size() const {//返回size_,不能改变其值,因此用const函数
return size_;
}
5、const修饰函数参数
防止传入的参数在函数体内被改变,仅对传指针和传引用有用(值传递传入的仅仅是实参)
void fun(const int i){
i = 10;
} //const没有任何意义
//-----------------------------------------
void fun(const char * src, char * des){ //保护源字符串不被修改,若修改src则编译出错。
strcpy(des,src);
}
void main(){
char a[10]="china";
char b[20];
fun(a,b);
cout<<b<<endl;
}
另外,const指针可以接受非const和const指针,但非const指针只能接受非const指针
(用primer的话就是,形参只是“以为”自己得到都是const指针)
传递进来的参数a是实参对象的副本,要调用构造函数来构造这个副本,而且函数结束后要调用析构函数来释放这个副本,在空间和时间上都造成了浪费,所以函数参数为类对象的情况,推荐用引用。但按引用传递,造成了安全隐患,通过函数参数的引用可以修改实参的内部数据成员,所以用const来保护实参。
void h(const A & a){
…………
…………
}
6 、const修饰函数返回值
也是用const来修饰返回的指针或引用,保护指针指向的内容或引用的内容不被修改,也常用于运算符重载。
归根究底就是使得函数调用表达式不能作为左值。
#include <iostream>
using namespace std;
class A {
private:
int i;
public:
A(){i=0;}
int & get(){
return i;
}
};
void main(){
A a;
cout<<a.get()<<endl; //数据成员值为0
a.get()=1; //尝试修改a对象的数据成员为1,而且是用函数调用表达式作为左值。
cout<<a.get()<<endl; //数据成员真的被改为1了,返回指针的情况也可以修改成员i的值,所以为了安全起见最好在返回值加上const,使得函数调用表达式不能作为左值
}
若改成 const int & get() {};
g++报错:
a.get()=1; //尝试修改a对象的数据成员为1,而且是用函数调用表达式作为左值。