" > " > " > " > "-6ren">
gpt4 book ai didi

c++ - 类里面不同的 "this"

转载 作者:太空狗 更新时间:2023-10-29 20:34:17 25 4
gpt4 key购买 nike

我在类里面玩耍并发现了这种好奇心

#include <iostream>
#include <Windows.h>

class pint {
public:
pint() { std::cout << "ctor >> " << this << std::endl; };
~pint() { std::cout << "dtor >> " << this << std::endl; };
pint(int x) { std::cout << "set 1. >> " << this << std::endl; };
pint& operator = (const pint& a) { std::cout << "set 2. >> " << this << " | a >> " << &a << std::endl; return *this; };
};

int main()
{
pint * x1 = new pint;
*x1 = 8;
*x1 = 9;

std::cout << "---------------------" << std::endl;

pint * x2 = new pint;
*x2 = 8;
*x2 = 9;

std::cout << "---------------------" << std::endl;

delete x1;
delete x2;

while (!GetAsyncKeyState(VK_RETURN))
Sleep(1);

return 0;
}

输出:

ctor >> 008731E8
set 1. >> 005BF9A7
set 2. >> 008731E8 | a >> 005BF9A7
dtor >> 005BF9A7
set 1. >> 005BF9A7
set 2. >> 008731E8 | a >> 005BF9A7
dtor >> 005BF9A7
---------------------
ctor >> 00873288
set 1. >> 005BF9A7
set 2. >> 00873288 | a >> 005BF9A7
dtor >> 005BF9A7
set 1. >> 005BF9A6
set 2. >> 00873288 | a >> 005BF9A6
dtor >> 005BF9A6
---------------------
dtor >> 008731E8
dtor >> 00873288

原因:

  • 全类“这个”不一样吗?
  • 输出的第一部分是“set 1”。同样,输出的第二部分是“set 1”。不同?
  • “第 1 组。”与ctor不同? (如果是因为制作新物体或类似的东西,为什么要制作它?)
  • “a”等于“第 1 组”。 “ctor”/“dtor”(最后)等于“set 2”。 ?
  • “第 1 组。”调用 dtor?

最佳答案

这里有趣的是,您拥有的不仅仅是一个对象!你生成一些临时的。

*x1 = 8;

pin 类没有operator=(int),但它可以通过int 生成一个pint 对象。因此构造函数 pint(int) 被调用。现在可以将具有新地址的新对象提供给 operator(const pint&)

这就是您看到“set1”文本的原因。 “8”首先会创建一个临时品脱对象,它有一个新地址。

如果你添加:“魔法”消失了:

pint& operator = (const int a) { std::cout << "set 3. >> " << this << " | a >> " << &a << std::endl; return *this; };

另一种查看编译器生成带有能够执行“不需要的转换”的构造函数的中间临时值的方法,您可以使转换构造函数显式

使用:

explicit pint(int x){...}

现在你的编译器给你一个错误!

关于c++ - 类里面不同的 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49637611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com