64,654
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
struct Student
{
int number;
string name ;//如果我把这行改为string name就出错,为何?
float score;
};
Student stu[3] = {{110, "yang", 100}, {111, "xiao", 99}, {112, "ying", 98}};
ofstream outfile ("stud.dat", ios::binary|ios::out);
if (!outfile)
{
cerr < < "open error!" < < endl;
exit (1);
}
outfile.write ((char *) &stu[0], sizeof (stu));
for (int i = 0; i < 3; i++)
{
//outfile.write ((char *)&stu[i], sizeof (stu[i]));
cout < < stu[i].number < < endl;
cout < < stu[i].name < < endl;
cout < < stu[i].score < < endl < < endl;
}
outfile.close ();
return 0;
}
楼主最主要的理解误区在于,认为string,char []都是字串的表达形式,应该string和char []相差无几
的确,从某中意义上来说,string就是字串,和char* char[]操作起来就那么回事,但string作为c++
中引入的类结构来说,差别还是蛮大的
string test;
sizeof(test) 如果是win32的系统应该是32
string test="lfjslfslkfjs";
sizeof(test) 仍然是32
char buffer[32];
sizeof(buffer); 其值为32
char buffer[64];其值为64
上面的简单语句说明什么问题? string结构的大小并不由字符的多少决定,那字符到底分配到哪里了呢?
答案就是,string结构中定义由char* ELE成员,这个ELE始终以指针的姿态存在,因此sizeof(ELE)始终
为4,这就是为何test的字符改变而sizeof的值不变的道理,而char* 由string类内部的内存分配器为其
开辟内存(至于在哪开辟内存,那是由string的实现决定)
如果简单的memcpy赋值给string类型,string内部的内存分配器永远都不会工作,字串永远不会被指针ELE
得到!
就讲那么多了,希望对楼主有所帮助!
#include <iostream>
#include "headerfile1.h"
#include "headerfile2.h"
using namespace std;
int main ()
{
Ns1::Student stu1 (27, "yang", 100);
stu1.display ();
cout << Ns1::fun (2, 2) << endl;
Ns2::Student stu2 (28, "xiao", 99);
stu2.display ();
cout << Ns2::fun (2, 2) << endl;
return 0;
}
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
namespace Ns1
{
class Student
{
public:
Student (int n, string nam, int a)
{
number = n;
name = nam;
age = a;
}
void display ()
{
cout << "number:" << number << endl;
cout << "name:" << name << endl;
cout << "age:" << age << endl;
}
private:
int number;
char * name;//字符指针,编译出错!!!
int age;
};
double fun (double a, double b)
{
return sqrt (a - b);
}
}
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
namespace Ns2
{
class Student
{
public:
Student (int n, string nam, float s)
{
number = n;
name = nam;
score = s;
}
void display ()
{
cout << "number:" << number << endl;
cout << "name:" << name << endl;
cout << "age:" << score << endl;
}
private:
int number;
char * name; //此处是指针!若改为字符数组也不行!@!!
float score;
};
double fun (double a, double b)
{
return sqrt (a + b);
}
}