#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
using namespace std;
void print(ostringstream&, ofstream&);
int main()
{
char* p;
int* pint;
ofstream fout("result.txt");
string s = "ABCDEFG";
int n = 33;
float x = 2.718;
ostringstream oss;
print(oss, fout);
oss << s;
print(oss, fout);
oss << " " << n;
print(oss, fout);
oss << " " << x;
print(oss, fout);
/*
p = &oss; //这是强类型匹配,不允许直接取地址
cout << "*(p-5) = " << *(p-5) << endl;
*/
p = &s[0]; //强类型匹配,只能这么做
fout << "p = " << p << endl;
fout << "&s[0] = " << &s[0] << endl;
fout << "&p = " << &p << endl;
fout << "&s = " << &s << endl;
pint = (int*)(&s[0]);
fout << "&s[0] = " << pint << endl;
pint = (int*)(&p+sizeof("ABCDEFG"));
fout << "(int*)(&p+sizeof(\"ABCDEFG\")) = " << *pint << endl;
fout << "*(p-1) = " << *(p-1) << endl;
fout << "--p = " << --p << endl; //这后边两个是不可打印字符
fout << "sizeof(string)+sizeof(s)+sizeof(x)+sizeof(n)+sizeof(oss)="
<< sizeof(string)+sizeof(s)+sizeof(x)+sizeof(n)+sizeof(oss) << endl;
p = (char*)(&p);
for (int i=0; i<15; i++)
{
fout << "p+" << i << " = " << (char*)(&p+i) << endl;
if (9==i || 8 == i || 7 == i)
{
//fout << "static_cast<int>(*p) = " << static_cast<int*>(p) << endl; 不能转换指针
fout << "static_cast<int>(*p) = " << static_cast<int>(*p) << endl; //可以转换指针所指数据
//pint = p;
//fout << "*pint = " << *pint << endl;
}
}
fout << "p+sizeof(int)+1 = " << p+sizeof(int)+1 << endl;
fout << "p+sizeof(string) = " << p+sizeof(string) << endl;
fout << "p+sizeof(\"ABCDEFG\") = " << p+sizeof("ABCDEFG") << endl;
fout << "p+sizeof(\"ABCDEFG\")+1 = " << p+sizeof("ABCDEFG")+1 << endl;
fout << "p+sizeof(\"ABCDEFG\")+1 = " << p+sizeof("ABCDEFG")+1 << endl;
//p = (char *)(&p-sizeof(pint)-sizeof(fout)-sizeof("result.txt")-sizeof(string)-sizeof(s));
//下潜500行都找不到
fout << "*p = " << *p << endl;
for (int i=0; i<1000; i++)
{
fout << "p-" << i << " = " << *(p-i) << endl;
}
system("pause");
return 4;
}
void print(ostringstream& oss, ofstream& fout)
{
cout << "oss.str() = \"" << oss.str() << "\"" << endl;
fout << "oss.str() = \"" << oss.str() << "\"" << endl;
}
注意:这里下潜500字符,都没有找到串"ABCDEFG"。其实我犯笨了,因为print用的是引用,拷贝的是ostringstream对象的地址值。
也就是说"ABCDEFG"就只有一个。然后它的位置在p+1上。