假设我有这个简单的程序
#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/