file1.cpp
int ext;
file2.cpp
extern const int ext2=12;
apple.cpp
class apple
{
private:
int people[100];
public:
apple(int i);
const int apple_number;
void take(int num) const;
int add(int num);
int add(int num) const;
int getCount() const;
};
const.cpp
#include <iostream>
#include "apple.cpp"
using namespace std;
// construct;
apple::apple(int i) :apple_number(i) {}
//
int apple::add(int num)
{
take(num);
return 0;
}
int apple::add(int num) const
{
take(num);
return 0;
}
void apple::take(int num) const
{
cout << "take fun" << num << endl;
}
int apple::getCount() const {
take(1);
return apple_number;
}
void f(const int i)
{
// 用於限定不可以修改參數.
//i++;
}
extern int ext;
// 特別注意這個, 在另外一個文件中, 是通過extern 和const 修飾的,
// 外部 extern const int ext2=12;
// extern int ext2; 報錯,
// const int ext2; 報錯.
// extern const int ext2; 正常,
// 有初始值. 外部 const int ext2=12
// extern int ext2; 報錯,
// const int ext2; 報錯.
// extern const int ext2; 報錯,
// 無初始值. 外部 const int ext2;
// extern int ext2; 報錯,
// const int ext2; 報錯.
// extern const int ext2; 報錯
extern const int ext2;
// 總結:
// 1 在使用了const後, 必須顯示的申明爲 extern ,在跨文件的模式下, 說明 const 是一個局部的.
// 2 在使用了const後, 必須顯示的賦值.
// 3 在使用了const後 ,使用的地方必須類型一致.
int main()
{
const int a = 1 + 1;
cout << ext + 10 << endl;
cout << ext2 + 12 << endl;
const int b = 10;
//b = 0;
const string s = "helloworld";
cout << s << endl;
const int* ptr = &a;
ptr = &b;
// *ptr = 10; 這個是錯誤的, 如果這麼寫了, 實際修改的是, 指針所指對象的值 ,
// 說白了, 就是int對象是不可以修改的,
const int p = 10;
const void* q = &p;
//void* m = &p; 類型不匹配, 申明不可以通過q 來修改p的值. 如果是這樣就容易被修改了,
int num = 10;
int num1 = 12;
int* const ptr1 = #
int* t = #
//ptr1 = &num1; 這個錯誤說明了, 該指針的值是不可以修改的,
*ptr1 = 11; //說明指針所指對象的值是可以修改的,
cout << *ptr1 << endl;
// 如上所示, 重點修飾的是指針,
// 總結 : 如果const在*的左邊, 則說明指針指向的對象的值不可以修改,
// 如果const在* 的右邊, 則說明指針本身是不可以被修改的,
apple app(2);
cout << app.getCount() << endl;
app.add(10);
const apple appb(3);
appb.add(100);
return 0;
return 0;
}
博主的原文鏈接 : https://github.com/Light-City/CPlusPlusThings/tree/master/basic_content/const ,非常感謝博主的分享.