c++ - the overloaded pointer operator

本文介绍了一个C++示例,展示了如何为智能指针类ScreenPtr重载解引用操作符(*)和成员访问操作符(->)。通过这些重载,可以像使用普通指针一样使用ScreenPtr,例如调用其指向的对象的方法move()。

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

YOu can overload the -> or the * operator, which is callled the reference and dereference operator separtely...

 

You can overload the operator if you see necessary, here is soem cdoe shows how you can use it. 

 

the header file 

 

 

/**
* file 
*   Screen.h
*
*  description:
*   this is the header file definition of the screen and the ScreenPtr
*/



class Screen
{
public:
	void move(int x, int y);
private:
protected:
};

class ScreenPtr
{
public:
	ScreenPtr(Screen *ptr_) : ptr(ptr_) { }
	Screen& operator*() { return *ptr; } 
	Screen* operator->() { return ptr; }
	~ScreenPtr() { delete ptr; } // we shall we define the operator as well
private:

	Screen *ptr;
protected:
};
 

the cpp implementation file. 

 

 

/**
* file 
*   Screen.h
*
*  description:
*   this is the header file definition of the screen and the ScreenPtr
*/

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

using std::cout;
using std::endl;
using std::cerr;



void Screen::move(int x, int y) 
{
	cout << "Screen move -> x: " << x << " y: " << y << endl; 
}

/**
*  point is examined to determine its type, if point is a pointer of some class type, the statement use the semantics of the built-in members
* access operator new . if  point is an object or a reference of some class type, the class is examined for an overloaded member access operator arrow.
*/

void test_use_of_ptr_overload() 
{
	Screen *screen = new Screen();
	ScreenPtr ptr(screen);
	ptr->move(1, 2);
}

 

one important thing about the semantic of the -> and * operator.

 

 

point is examined to determine its type, if point is a pointer of some class type, the statement use the semantics of the built-in members. access operator new . if  point is an object or a reference of some class type, the class is examined for an overloaded member access operator arrow.

 

### 解决 VSCode 中 JSON 文件只读问题的方法 当遇到在 VSCode 编辑器中无法编辑 JSON 文件的情况时,这通常是因为文件被标记为只读。为了取消这种状态并允许正常编辑,可以通过调整设置来解决问题。 对于因权限或环境配置引起的只读情况,建议按照如下方式处理: 通过修改VSCode的特定设置选项能够有效解决该类问题,在VSCode内依次执行以下命令可达到目的:点击左下角齿轮图标进入设置界面;利用搜索栏查找`Shebang`相关配置项;找到名为`Run Code Configuration: Respect Shebang`的选择框,并确保其处于启用状态[^4]。不过需要注意的是,上述操作主要是针对由插件引发的只读状况,而并非操作系统层面设定的真正意义上的只读属性。 另外一种常见的情形是由于文件本身或者所在磁盘分区设置了只读标志位所造成的。此时应当检查目标JSON文档以及它所在的存储设备的状态,确认是否有外部因素干扰写入权限。如果是这种情况,则需前往资源管理器或者其他相应工具里解除对应的限制条件后再尝试编辑。 最后值得注意的一点是在某些特殊环境下(比如使用PlatformIO开发框架配合SDCC编译器),可能还会碰到因为IDE未能正确解析自定义语法而导致误报只读警告的现象。对此可通过适当调整预处理器宏定义的方式绕过此类伪异常,例如向项目源码引入`__SDCC_SYNTAX_FIX`参数以便让VSCode更好地理解非标准C语言结构[^2]。 尽管以上措施有助于缓解大多数场景下的只读难题,但在实际应用过程中仍应具体情况具体分析,必要时查阅官方文档获取更详尽的帮助信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值