|
楼主 |
发表于 2019-9-12 18:08:20
|
显示全部楼层
本帖最后由 bin554385863 于 2019-9-12 18:23 编辑
修改版
- #include <iostream>
- template <typename t>
- class ptr
- {
- private:
- t val;
- int Step;
- public:
- ptr() : val(0), Step(0) {} //默认构造
- ptr(t var) : val(var), Step(0) {} //普通变量参数构造
- ptr(t *pt) : val(*pt), Step(0) {} //指针参数构造
- ptr(const ptr &p) : val(p.val), Step(0) {} //复制构造
- void setPtrOffset(int step = 0) //指针偏移值,-负值反向
- {
- Step = step;
- }
- void setValue(t var) //设值
- {
- *(&val + Step) = var;
- }
- t *getPtrValue() //取地址.负值反向
- {
- return (&val + Step);
- }
- t getValue() //取值,负值反向
- {
- return *(&val + Step);
- }
- int getPtrOffset(ptr p) //取得偏移值
- {
- return p.getPtrValue() - this->getPtrValue();
- }
- ~ptr() {}
- };
- int main(int argc, char const *argv[])
- {
- using namespace std;
- int a = 100, b = 54;
- int *p;
- p = &b;
- cout << "a = " << &a << "---" << a << '\n'
- << endl;
- ptr<int> pt;
- cout << "pt默认数据" << endl;
- cout << "pt = " << pt.getPtrValue() << "---" << pt.getValue() << '\n'
- << endl;
- pt = a;
- cout << "pt = a" << endl;
- cout << "pt = " << pt.getPtrValue() << "---" << pt.getValue() << '\n'
- << endl;
- pt.setValue(52.0);
- cout << "pt.setValue(52.0)" << endl;
- cout << "pt = " << pt.getPtrValue() << "---" << pt.getValue() << '\n'
- << endl;
- ptr<int> pp = p;
- cout << "pp = p" << endl;
- cout << "pp = " << pp.getPtrValue() << "---" << pp.getValue() << '\n'
- << endl;
- cout <<"pt.getValue() - pp.getValue() = " <<pt.getValue() - pp.getValue() << endl;
- cout<<endl;
- cout << "pt.getPtrOffset(pp) = "<<pt.getPtrOffset(pp)<<endl;
- return 0;
- }
复制代码
---------------------------------------------------------------------------------------------------
Microsoft Windows [版本 10.0.16299.1087]
(c) 2017 Microsoft Corporation。保留所有权利。
E:\Users\86184\Documents\Code>c:\Users\86184\.vscode\extensions\ms-vscode.cpptools-0.25.1\debugAdapters\bin\WindowsDebugLauncher.exe --stdin=Microsoft-MIEngine-In-jroasrly.yxx --stdout=Microsoft-MIEngine-Out-lyphkmma.3mq --stderr=Microsoft-MIEngine-Error-4m0113jj.ua1 --pid=Microsoft-MIEngine-Pid-afflexgm.020 "--dbgExe=E:\My Program\MinGW\bin\gdb.exe" --interpreter=mi
a = 0x61fef8---100
pt默认数据
pt = 0x61feec---0
pt = a
pt = 0x61feec---100
pt.setValue(52.0)
pt = 0x61feec---52
pp = p
pp = 0x61fee4---54
pt.getValue() - pp.getValue() = -2
pt.getPtrOffset(pp) = 6
E:\Users\86184\Documents\Code> |
|