首页 > linux > 学习c++

学习c++

作者:bin

在linux下,首先检查环境是否支持c++

g++ -v

编译,与运行

g++ youfilename.cpp -o yourfilename

./youfilename

一、指针的应用

const int *ip = 0;

int var = 20;

ip=&var;

解释:

const int *ip = 0,标识ip是一个指针,并且可以指向任意一个int的变量或者int常量。并且不可以通过(ip)指针去修改这个值

ip=&var; 将ip指向var地址

ip = 100 //error: assignment of read-only location ‘* ip’

提示只读属性,及不能修改他的值。

int a=2;

int &b=a;//这个声明语句中的&是一个引用

int *p=&b;//这个指针初始化语句中的&是取地址运算符

应用场景:

int loadCfg(const char *pszCfgFile);

传入变量时候,传入指针。

loadCfg( &pszCfgFile );

通过pszCfgFile地址来使用loadCfg方法

学习代码记录:

#include <iostream>
 #include <ctime>
 #include <cstdlib>
 using namespace std;
 #define DOMAIN "www.zengbingo.com"
 const string SIGN = "lskSrj2@sk1";

//数据结构
 typedef struct Books{
 string title;
 string author;
 string subject;
 int book_id;
 } B;

int main(){
//标准输出
 cout << "hello to chinese is 'nihao'" << endl;
 cout << "size of int :" << sizeof (int) << endl;

//枚举
 enum { RED = 1, BLUE, YELLOW };
 cout << BLUE << endl;

cout << DOMAIN<< endl;

cout << SIGN << endl;

//获取随机数
 srand( (unsigned)time( NULL ));

int j= rand();

cout << j << endl;

//指针与引用
 int var = 20;
 int var2 = 30;
 const int *ip = 0;
 cout << "初始值,ip地址为:" << ip << endl;

ip=&var;
 cout << "var地址为:" << &var << endl;
 cout << "var的值为:" << var << endl;
 cout << "指针地址为:" << ip << endl;
 cout << "指针的值为:" << *ip << endl;
 ip=&var2;
 cout << "var地址为:" << &var << endl;
 cout << "var的值为:" << var << endl;
 cout << "var2地址为:" << &var2 << endl;
 cout << "var2的值为:" << var2 << endl;
 cout << "重置后,指针地址为:" << ip << endl;
 cout << "重置后,指针的值为:" << *ip << endl;

//时间
 time_t now = time(0);

tm *gtm = localtime(&now);

cout << "tm 时间为:" << gtm->tm_sec << endl;
 cout << "ctime 时间为:" << ctime(&now) << endl;

//结构指针与引用
 B b1;
 b1.title = "你好";
 cout << "结构体b1,title为:" << b1.title << endl;

B &b2 = b1;
 b2.title = "你好b2";
 cout << "[值引用]结构体b1,title为:" << b1.title << endl;
 cout << "[值引用]结构体b2,title为:" << b2.title << endl;

B *b3 = &b1;
 b3->title = "你好b3";
 cout << "[指针]结构体b1,title为:" << b1.title << endl;
 cout << "[指针]结构体b3,title为:" << b3->title << endl;

B *&b4 = b3;
 b3->title = "你好b4";
 cout << "[指针]结构体b1,title为:" << b1.title << endl;
 cout << "[指针]结构体b4,title为:" << b4->title << endl;

//标准的输入与输出流
 string name;
 cout << "请输入你的名字" << endl;
 cin >> name;
 cout << "你的名字为:" << name << endl;
 cerr << "T_T这是一条错误消息" << endl;

return 0;
 }

您必须 [ 登录 ] 才能发表留言!