-------------------------------------
典型例题6 :C++问题---sizeof(string)问题;
-------------------------------------
1 #include <iostream>
2 #include <string>
3
4 using namespace std;
5
6 class mystring{
7 friend ostream& operator<< (ostream& ostrm, const mystring& strData);
8 public:
9 mystring()
10 {
11 m_cpData = NULL;
12 m_nLength = 0;
13 }
14 ~mystring()
15 {
16 if (m_nLength != 0)
17 {
18 delete m_cpData;
19 m_cpData = NULL;
20 m_nLength = 0;
21 }
22 }
23 void operator = (const char* cpData);
24 int length(void);
25
26 protected:
27 const char* data(void) const;
28
29 private:
30 char* m_cpData;
31 int m_nLength;
32 };
33
34 //重载"="运算符, 以便使用 string a = "wdd"这样的赋值
35 void mystring::operator = (const char* cpData)
36 {
37 m_nLength = strlen(cpData);
38 m_cpData = new char[m_nLength];
39 memset(m_cpData, 0, m_nLength);
40 memcpy(m_cpData, cpData, m_nLength);
41 }
42
43 int mystring::length(void)
44 {
45 return m_nLength;
46 }
47 const char* mystring::data() const
48 {
49 return m_cpData;
50 }
51
52 //重载"<<"运算符, 以便使用 cout << strData; 来输出字符串
53 ostream& operator<< (ostream& ostrm, const mystring& strData)
54 {
55 if (strData.m_nLength != 0)
56 {
57 ostrm << strData.m_cpData;
58 }
59 return ostrm;
60 }
61
62 int main(void)
63 {
64 //定义(对象)变量
65 mystring strTestA, strTestB;
66 string strTestC;
67
68 //赋值
69 strTestA = "Hello World";
70 strTestB = "World";
71 strTestC = "Hi";
72 //输出string的长度,三个值是一样的.
73 cout <<sizeof(mystring) << " " <<sizeof(strTestA) <<
74 " " <<sizeof(strTestB) <<
75 " " <<sizeof(string)<<" "<<sizeof(strTestC) << endl;
76
77 //输出字符串的长度
78 cout << strTestA.length() <<" " << strTestB.length()<<" "<<strTestC.length()<< endl;
79
80 //输出字符串
81 cout << strTestA << endl;
82 cout << strTestB << endl;
83 cout << strTestC << endl;
84 return 0;
85 }
--------------------------
haiping@ubuntu:~/program/yo0913$ ./a.out
8 8 8 4 4
11 5 2
Hello World
World
Hi
-------------------------
结果分析:
可以看到,我自己实现的string类类型大小为8(实际上为sizeof(char*)+sizeof(int)),如果增加一个私有变量int类型,这个sting类类型大小为12;而标准c++的string类类型大小为4,说明只有一个指针;
C++问题---sizeof(string)问题
最新推荐文章于 2023-04-13 11:32:57 发布