2017-06-04 33 views
-5

我有一个类foo这样的:差异分配char型和int类型在C++

class foo 
{ 
private: 
    int* a; 
public: 
    foo() 
    { 
     a = new int[4]; 
     cout << "a" << endl; 
    } 
}; 

当我创建了一个名为foo1新的对象,然后我调试,所以分配行后,它产生的结果:
a 0x005a4580 {-842150451}
但是当我在类定义char -s全部更换int -s,则产生了一个令人失望的结果:

a 0x005694a0 "ÍÍÍÍýýýý\x6ŒÒ•\x5Ÿ" 

说的a大小现在是大于4
我不知道发生了什么。你能给我一个解释吗?


全码:

#include <iostream> 
#include <string> 
using namespace std; 

class String 
{ 
public: 
    String(char* data) 
    { 
     setSize(0); 
     while (*(data + size) != '\0') 
      size++; 
     this->data = new char[size]; 
     //need to allocate memory for 'data' pointer because 'data' pointer is now on the stack and the data must be on the heap 
     memcpy(this->data, data, size * sizeof(char)); 
    } 
    void operator=(String rhs) 
    { 
     if (this->data != NULL) 
      delete[] this->data, data = NULL; 
     this->data = new char[rhs.getSize()]; //allocate 
     memcpy(this->data, data, size * sizeof(char)); 
    } 
    int getSize() 
    { 
     setSize(0); 
     while (*(data + size)) 
      size++; 
     return size; 
    } 
    void setSize(int size) 
    { 
     this->size = size; 
    } 
    void display() 
    { 
     for (int i = 0; i < size; i++) 
      cout << *(data + i); 
    } 
    ~String() 
    { 
     if (data != NULL) 
      delete[] data, data = NULL; 
    } 
private: 
    char* data; 
    int size; 
}; 

void main() 
{ 
    String a("abcd"); 
    String b("1"); 
    a.display(); 
    cout << endl; 
    cout << b.getSize() << endl; 
    a = b; 
    cout << a.getSize() << endl; 
    system("pause"); 
} 
+0

此代码与您的问题陈述不符。另外什么是“char-s”? – user3344003

+0

@ user3344003'char'的复数。 – melpomene

+1

cout <<“a”<< endl;应该只打印“a”。 – user3344003

回答

3

无论您使用的是看a不知道你分配多少。它只知道类型。

在第一个版本中,它看到int *,所以它显示一个单一的int

在第二个版本中,它看到的是char *,所以它认为它是一个C字符串,并打印第一个字节中的任何内存。

+0

就像你说的,我们不知道'a'' char'的大小?顺便说一下,是否有限制'a'' char'的大小? –

+0

@NguyễnTrọng我不明白你在问什么。根据定义,'char'的大小是1。 – melpomene