c++点滴

好久没有用C++了,最近写paper,发现做实验java的效率确实比不过C++,花点时间稍微翻一下C++的书。整理一些东西


1、设置输出精度

float pi=3.1415926;

cout.precision(3)

cout<<pi<<endl;

或者

cout<<setprecison(3)<<pi<<endl;


2、创建预处理宏

#define maximum(a,b) (a<b)?b:a

int main()

{

int max=maximun(5,3);

}


3、一些数据结构

struct Person{

string name

int id

}

Person p1,p2;

p1.name="hi";

p1.id=5;


all members of a union point to the same data in memory.

union one_union

{

int a;

int b;

}

one_union union1;

union1.a=10;

由于是union,所以union1.b也被设置为10


enumeration

enum day

{

sunday,

monday

tuesday

}

enum day today=sunday;

if(today==sunday)

{

}


5 变量的作用域

automatic variable are local to a block and so have local scope, internal linkage

eternal variables are declared outside any function, are available to all files in a program, and have global scope, external linkage

external static variables are external variables declared with the static keyword and are available to all code in the file, but they are restricted to the file they are defined in and so have global scope, internal linkage

external constant variable are external variables declared with the const keyword and are available to all code in the file, but they are restricted to the file they are defined in and have global scope, internal linkage

static variables are automatic variables declared with the static keyword, are confined to a block, and so have local scope internal linkage.

example 1

string color("red");

void local();

int main()

{

cout<<"global color is "<<color<<endl;

local();

return 0;

}

void local()

{

string color("blue");

cout<<local color<<color<<endl;

}

输出:

global:red

local:blue


全局变量的测试2

file1.cpp

int value=1;

int main()

{

cout<<"In file one....value1"<<value<<endl;

}

在file2.cpp中

extend int value1;

void second_file_values()

{

cout<<"in file two...value1:"<<value1<<endl;

}


例子3:

int total(){int total=0;total++;return total;}

int sum(){static int sum=0;sum++;return sum;}


cout<<total()<<sum();

//print 1 and 1

cout<<total()<<sum();

//print 1 and 2

6 模板函数

template <typename T>

void add_one(T &n)

{

n++;

}

7、inline 函数

一般的函数调用,需要跳转指令。 所以需要保存执行场景。用inline的话,可以将代码直接嵌入到调用的地方,从而save a little execution time.

inline int sq(int value){return value*value;}

void main()

{

int data=5;

cout<<data<<sq(5)<<endl;


8、指定默认参数

long adder(int op1, int op2=1){return op1+op2;}

cout<<adder(5,7);

cout<<adder(5);

值得注意的是如果指定一个默认值给一个参数,那么该参数后面的所有参数都必须指定默认值

int cal(int v1,int v2,int v3=1,int v4=2);


9、可变长度的参数 handing a varible number of arguments

int adder(int ...);

int main()

{

cout<<"the sum="<<adder(3,1,2,3)<<endl;

}

int adder(int number...)

{

int result=0;

va_list list;

va_start(list,number);

for(int loop_index=0;loop_index<number;loop_index++)

{

int integer=va_arg(list int);

result+=integer;

}

va_end(list);

return result;

}

The sum=1+2+3=6;





你可能感兴趣的:(C++,String,list,File,Integer,variables)