顶层const指针type * const p;底层const指针type const* p

顶层const指针不能改指向(如同顶层const常量不能改值),当指向变量时可以通过顶层const指针改变量的值,因此,顶层const指针不能指向常量;
底层const指着可以改指向,但不能通过其改所指对象的值

// TopBottomconst.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>

int _tmain(int argc, _TCHAR* argv[])
{
	int n=9;
	const int cn=n;
	int const *pcn=&n;   //底层const指针指向变量
	*pcn=8; //err"表达式必须是可修改的左值" 即不允许通过底层const改(赋值)指向对象 即使是指向变量
	pcn=&cn; //底层const指针指向常量  (底层const可以改指向)
	*pcn=8;  //err"表达式必须是可修改的左值" 即不允许通过底层const改(赋值)指向对象 指向常量更不应该改值
	int *const pcn3=&n;  //顶层const指针指向变量
	*pcn3=8;             //顶层const指针指向变量时可以通过其修改指向对象
	pcn3=&cn;//err"表达式必须是可修改的左值" 即顶层const不允许改指向(值)
	int const cn2=n;
	int *const pcn4=&cn2; //err"const int*类型的值不能初始化int*const类型的实体"
	                      //即 顶层const指针不能指向常量(顶层const对象)

	system("pause");
	return 0;
}
#include <QCoreApplication>
#include <iostream>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    char *pch=new char;
    strcpy(pch,"Hello Qt!\0");
//    ostream std::cout;
    std::cout<<*pch<<std::endl;
    const char *pch2="Hello Qt! 2\0";
    std::cout<<*pch2<<std::endl;
    strcpy(pch,"Hello Cpp!\0");
    std::cout<<*pch2<<std::endl;

    char *const pch3=new char;
    strcpy(pch3,"Hello Qt! 3\0");
    pch3[0]='h'; //顶层指针改值,没毛病
    std::cout<<*pch3<<std::endl;
    pch3 = pch; //顶层指针尝试改指向,报错"assignment of read-only variable 'pch3' "
    std::cout<<*pch3<<std::endl;

    const char str[] = "Hello Qt! 4\0";
    const char *pch4=str;
//    strcpy(pch4,str);
    pch4[0]='h';//底层指针尝试改值,报错"assignment of read-only location '* pch4' "
    std::cout<<*pch4<<std::endl;
    pch4=pch;//底层指针尝试改指向,没毛病

    const char * const pch5=str;
    pch5[0]='h';//顶层常指针尝试改值,报错"assignment of read-only location '*(const char*)pch5' "
    std::cout<<*pch5<<std::endl;
    pch5=pch;//顶层常指针尝试改指向,报错"assignment of read-only variable 'pch5' "

    return a.exec();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值