c++ - 结构变量包含什么?

标签 c++ variables types struct

假设我有这个简单的程序

#include <iostream>
using namespace std;

struct teststruct
{
   int n;
   long l;
   string str;
};

int main()
{
   teststruct wc;

   wc.n = 1;
   wc.l = 1.0;
   wc.str = "hello world";

   //cout << wc << endl; // what is wc by itself?
   cout << &wc;  // contains the memory address to the struct?
   return 0;
}

我正在尝试了解 wc 中的内容?当我用变量名 wc 声明一个结构类型时; wc是什么它是指向内存地址的指针吗?我试图找出内容,但代码给了我一个错误。你能解释一下 wc 是什么吗

最佳答案

what is wc? Is it a pointer to a memory address?

不,它是一个大到足以包含 teststruct 的所有成员的存储 block .

在这种情况下,它具有自动存储,这意味着它的持续时间与包含它的代码块一样长 - 在这种情况下,直到 main() 结束。 .它存储位置的细节是特定于实现的,但实际上它通常存储在线程堆栈的临时区域(堆栈框架),在函数开始时创建并在函数退出时销毁.

关于成员如何位于该存储中的确切细节也是特定于实现的。

I've tried to cout the contents, but the code gives me an error.

这仅适用于具有 << 的类型运算符重载。标准库对所有基本类型和指针以及某些库类型(如 std::string)执行此操作。 ;但是如果你想支持你自己的类型,那么你需要提供你自己的重载,例如:

std::ostream & operator<<(std::ostream & s, teststruct const & t) {
    return s << t.n << ',' << t.l << ',' << t.str;
}

cout << wc << endl; // prints "1,1,hello world"

关于c++ - 结构变量包含什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11317486/

相关文章:

c++ - 如何在结构数组中显示学生姓名以及 GPA 高于平均水平的 ID

xcode - NSClasses 与 Swift 新类

c++ - move 和转发案例使用

c++ - mysql和c++连接

php - Laravel 将路由参数修改为 name 列而不是 id

c# - 通过层传递类型

java - 为什么下面的代码会导致 javac 崩溃?可以做些什么呢?

arrays - 循环中的数组修改

c++ - std::remove_if 来自 std::vector 的多态 std::unique_ptr

java - 分配给在没有实例化对象的方法中声明的类变量