溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

const的用法

發(fā)布時(shí)間:2020-08-02 05:12:56 來(lái)源:網(wǎng)絡(luò) 閱讀:403 作者:神跡難覓 欄目:編程語(yǔ)言

在other.cpp中


#include<iostream>

using namespace std;

#const int global=5;  //加入const 會(huì)讓global原來(lái)的外部的鏈接型轉(zhuǎn)為內(nèi)部鏈接性。

extern const int global=5;

void print(){

cout << global << endl;

}


在main.cpp中

#include<iostream>

using namespace std;

extern const int global;//這里會(huì)報(bào)錯(cuò),因?yàn)間lobal中只有other.cpp可以用。

int main(){

cout << global << endl;

system("pause");

return 0;

}

若想這個(gè)const常量可以被main.cpp中使用,可以按藍(lán)色字體的加個(gè)extern就可以了。

注意:若在other.cpp文件中g(shù)lobal變量不具有外部鏈接性,照樣可以通過(guò)他的函數(shù)print()訪問(wèn)

函數(shù)默認(rèn)具有外部鏈接性!



這里我還想提醒一下。任何變量或數(shù)組的賦值,在main()和一些函數(shù)外,只能在定義的時(shí)候賦值。

不得定義后再賦值。

#include<iostream>

using namespace std;

//extern const int global;

float * pd1 = new float[20];

int s=5;//可以在定義是直接賦值。

//s = 5;錯(cuò)的

int a[100];

//a[1]=3;錯(cuò)的,


int main(){

pd1[3] = 100.0;

cout << pd1[1] << endl;

float * pd2;

pd2 = new float[20];

pd2[0] = 100.00;

cout << *pd2 << endl;

delete pd2;

        delete pd1;

system("pause");

return 0;

}



const int * func; //是一個(gè)指向int型常量的指針,這個(gè)常量不可改變但指針可以改變

int *const func; //將func不可以自加。


這里指向常量的指針可以指向變量。

int a = 10; //變量

const int * ptr = &a;//指向常量的指針可以指向變量。

a = 3;


但是

const int a = 10; //變量

const int * ptr = &a;//指向常量的指針可以指向變量。

//a = 3; 會(huì)報(bào)錯(cuò)


向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI