#include <iostream>
#include <string>
void* operator new(size_t size) {
std::cout << "Allocated: " << size << " Bytes\n";
return malloc(size);
}
void operator delete(void* var) {
std::cout << "Deleted\n";
free(var);
}
int main() {
std::string name0 = "Ahmed Zaki Marei";
//std::string name1 = "Lara Mohammed";
std::cout << name0 << "\n";
//std::cout << name1 << "\n";
}
Run Code Online (Sandbox Code Playgroud)
当我尝试运行此代码时,它给了我以下输出:
Allocated: 8 Bytes
Allocated: 32 Bytes
Ahmed Zaki Marei
Deleted
Deleted
Run Code Online (Sandbox Code Playgroud)
为什么它先分配 8 个字节然后分配 32 个字节?有谁能解释一下吗?谢谢!:)
#include <iostream>
#define print(x) std::cout << x
#define println(x) std::cout << x << std::endl
struct Vector2 {
float x, y;
};
struct Vector4 {
union {
struct {
float x, y, z, w;
};
struct {
Vector2 a, b;
};
};
};
void PrintVector2(const Vector2& vector) {
println(vector.x << ", " << vector.y);
}
int main() {
Vector4 vector = { 1, 2, 3, 4 };
vector.x = 2;
vector.z = 500.0f;
PrintVector2(vector.a);
PrintVector2(vector.b);
}
Run Code Online (Sandbox Code Playgroud)
谁能解释一下这段代码发生了什么?,我不明白工会是什么以及它们是如何工作的:/!
这是输出
2, 2
500, …Run Code Online (Sandbox Code Playgroud)