其他
C++与C中的const关键字有何差别?
前言
修饰普通变量--只读
int main(void)
{
const int a = 10;
int *p = &a;
*p = 11;
printf("a=%d\n",a);
return 0;
}
看一个例子就明白了:
int main()
{
const int a = 10;
int *p = &a;
*p = 11;
return 0;
}
main.cpp:5:14: error: invalid conversion from ‘const int*’ to ‘int*’ [-fpermissive]
int *p = &a;
void test(const char* str)
{
char *p = (char*)str;
p[0] = '2';
}
int main(void)
{
char a[] = "12345";
test(a);
return 0;
}
作用在成员函数-不改变成员变量
class Test
{
private:
int a;
public:
void printA() const
{
a = 10;
}
};
int main()
{
Test test;
test.printA();
return 0;
}
main.cpp:9:13: error: assignment of member ‘Test::a’ in read-only object
a = 10;
即下面的声明是非法的:
修饰类成员变量--构造函数中初始化
class Test
{
private:
const int a;
public:
Test(int val):a(val){}
};
int main()
{
Test test(1);
return 0;
}
修饰引用
总结
int * const p;
int const * const p;