我有一个类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");
}
此代码与您的问题陈述不符。另外什么是“char-s”? – user3344003
@ user3344003'char'的复数。 – melpomene
cout <<“a”<< endl;应该只打印“a”。 – user3344003