const關鍵字
const關鍵字是c/c++語言中保留的一個關鍵字,用來限定一個變量是隻讀的,即不可變的;程序中使用const一定程度上可增加程序的健壯性;
大家都知道const所修飾的值(定義常量)是不可以被修改的
所以在這塊就說一下const和指針的關係
const和指針
1.常量指針
不能通過指針修改指針所指向變量的值,但是指針可指向別的變量;
eg:
int a=5;
const int *p=&a;
*p=20;//錯誤的,不能通過指針修改指針所指向變量的值
int b=10;
p=&b;//指針可指向別的變量
2.指針常量(指向常量的指針)–指針常量的值不能被修改,即不能存一個新的地址,不能指向別的變量;但是可以通過指針修改它指向的變量的值;
int a=5;
int *const p=&a;
*p=20;//正確,可以通過指針修改指針所指向變量的值
int b=10;
p=&b;//錯誤,指針不能指向別的變量
const和函數
const int func(const int a)const;
-修飾返回值const int func(); 不能修改返回值;
-修飾函數形參int func(const int a),函數體內不能修改形參a的值;
int fun()
{
a+=3;//在函數體內不能修改成員變量的值--錯誤
return a;
}
修飾類的成員函數int func()const; 函數體內不能修改成員變量的值,增加程序的健壯性
const對象只能調用const成員函數,不能調用普通成員函數;
而普通對象既可以調用const成員函數,也可以調用普通成員函數;
例如:
Point.h:
#ifndef POINT_H
#define POINT_H
#include <iostream>
using namespace std;
class Point
{
public:
Point(float a=0,float b=0);
void move(float a,float b);
void print() const;
private:
float x;
float y;
};
#endif
Point.cpp:
#include "Point.h"
#include <iostream>
using namespace std;
Point::Point(float a,float b):x(a),y(b){}
void Point::move(float a,float b)
{
x+=a;
y+=b;
}
void Point::print() const
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
main.cpp:
#include "Point.h"
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
const Point p;
p.print();
return 0;
}
this指針
每一個對象都“包含”一個指針指向對象自身,稱之爲this指針;
例:
#include <iostream>
using namespace std;
class Circle
{
public:
Circle();
void printfOnlyRadius();
private:
float radius;
float x_center;
float y_center;
};
Circle::Circle()
{
radius=10;
x_center=2;
y_center=2;
}
void Circle::printfOnlyRadius()
{
cout<<radius<<endl;
cout<<this->radius<<endl;
cout<<(*this).radius<<endl;
cout<<this<<endl;
}
int main()
{
Circle p;
p.printfOnlyRadius();
cout<<&p<<endl;
}
this指向調用者;當調用指向成員函數時,會默認將對象自身傳遞給該函數,在函數體內不直接使用對象名,而是使用this指針,this指針指向該對象,指向調用者;
類的靜態成員函數示例
靜態局部變量:函數結束後,靜態局部變量的內存空間不會被系統回收,下一次調用函數時會使用上一次退出時的值;
靜態全局變量和全局變量的區別:生命週期不變,作用域減小,靜態全局變量只能在它所聲明的源文件中使用,不能被extern引用;eg:char *student::teacher=" ";
示例代碼:
#include <iostream>
#include <string.h>
using namespace std;
class Employee
{
public:
Employee(const char *name_str)
{
next_id++;
id=next_id;
strcpy(name,name_str);//name=name_str
cout<<id<<" "<<name<<endl;
}
//靜態成員函數一般來操作靜態成員
static void acc_total(float f)//發一次工資放入total
{
total_pay+=f;
cout<<total_pay<<endl;
}
void print()
{
cout<<id<<",";
}
private:
int id;
char name[50];
static int next_id;
static float total_pay;
};
int Employee::next_id=0;
float Employee::total_pay=0;
int main()
{
Employee lucy("lucy");
Employee tom("tom");
Employee jary("jary");
lucy.acc_total(1000);
tom.acc_total(1000);
jary.acc_total(1000);
Employee::acc_total(1000);
return 0;
}
靜態成員函數只能訪問靜態成員,不能訪問非靜態成員;
而普通成員函數既可以訪問靜態成員,也能訪問費靜態成員