1

Say I have this simple program

#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;
}

I'm trying to understand what is in wc? When I declare a struct type with the variable name wc; what is wc? Is it a pointer to a memory address? I've tried to cout the contents, but the code gives me an error. Can you please clarify what is wc

4

4 回答 4

10

什么是厕所?它是指向内存地址的指针吗?

不,它是一个大到足以容纳所有成员的存储块teststruct

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

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

我试图找出内容,但代码给了我一个错误。

这仅适用于<<运算符重载的类型。标准库对所有基本类型和指针以及某些库类型(如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"
于 2012-07-03T19:15:20.260 回答
5

wcteststruct是自动存储类型的实例。每个其他细节都是特定于实现的,但在大多数情况下,实现使用堆栈作为自动存储区域。

&wc是 type 的表达式teststruct *,导致wc's 地址。

至于未问的问题(你为什么不问它?):要输出结构的内容,你必须一一输出它的成员:

cout << wc.n << ", " << wc.l << ", " << wc.str << endl;

但是,您的代码似乎存在误解;1.0是 type 的字面量float,也就是浮点数。您确定这是要存储在long变量中的内容吗?如果您想要long文字,请使用1L.

于 2012-07-03T19:06:41.683 回答
0

将 的实例teststruct视为一个连续的内存区域,用于包含其成员变量的值。打印时

    cout << &wc;

您正在输出变量的地址,即存储变量的内存位置。这是一个简单的答案,可能充满了详细的技术错误,但您问题的性质和措辞表明它可能为您描绘了一幅有用的画面。

于 2012-07-03T19:14:14.767 回答
0

wcteststruct是在堆栈上分配的类型的对象

于 2012-07-03T19:06:16.263 回答