typedef和const pointer定义

本文通过一个C++示例程序详细解释了在使用typedef声明指针时,const关键字的作用范围及其常见误解。通过对比不同变量声明方式,阐述了const修饰符在指针声明中的实际作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

假设以下语句

Typedef string *ptr;

Const ptr cstr;

很多人都认为cstr的真实类型是

Const string *cstr,但这是错误的。

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
	string s("hello world");
	string s1("you can not point me");
	typedef string *ptrsing;
	const ptrsing cstr1 = &s;
	ptrsing const cstr2 =&s;
	string *const cstr3 =&s;

	cstr1 = &s1;
	cstr2 = &s1;
	cstr3 = &s1;
	
	return 0;

}

错误的原因是把typedef当做文本扩展了,声明const ptr时,const修饰的是ptr指针,这是一个指针,因此定义等价于

String * const cstr。


#ifndef ALLOCATOR_HPP #define ALLOCATOR_HPP #include <stddef.h> #include <limits> template <typename T> class Allocator { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef T value_type; //Allocator::rebind<T2>::other template <typename V> struct rebind { typedef Allocator<V> other; }; pointer address(reference value) const { return &value; } const_pointer address(const_reference value) const { return &value; } Allocator() throw() { } Allocator(const Allocator &) throw() { } //不同类型的allcator可以相互复制 template <typename V> Allocator(const Allocator<V> &other) { } ~Allocator() throw() { } //最多可以分配的数目 size_type max_size() const throw() { return std::numeric_limits<size_type>::max() / sizeof(T); } //分配内存,返回该类型的指针 pointer allocate(size_type num) { return (pointer)(::operator new(num * sizeof(T))); } //执行构造函数,构建一个对象 void construct(pointer p, const T &value) { new ((void*)p) T(value); } //销毁对象 void destroy(pointer p) { p->~T(); } //释放内存 void deallocate(pointer p, size_type num) { ::operator delete((void *)p); } }; template <typename T, typename V> bool operator==(const Allocator<T> &, const Allocator<V> &) throw() { return true; } template <typename T, typename V> bool operator!=(const Allocator<T> &, const Allocator<V> &) throw() { return false; } #endif讲解这段代码
最新发布
03-27
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值