我是一名大学学生。我主要使用 Java 工作,C++ 对我来说很陌生,所以我可能会犯很多愚蠢的错误,而且我还有即将到来的考试要应对。别对我太严厉。
注意:我不能使用 C++ std::string 因为由于大学任务我需要使用 C 字符串!
参考我的研究和我提出的关于指针和问题const
参数(你发现here https://stackoverflow.com/questions/45212435/c-const-arguments-in-funcitions)我尝试搞乱内存管理,但似乎没有效果,或者我只是误解了一些方面sizeof
或某些元素的实际大小。
这是我的班级人物:
人物.cpp
using namespace std;
Person::Person()
{
Person::name = new (char[64]);
Person::adress = new (char[64]);
Person::phone = new (char[64]);
cout << "standard constructor called; object created, allocated " << sizeof(name) << "+" << sizeof(adress) << "+" << sizeof(phone) << "bytes" << endl;
}
Person::Person(const char *name, const char *adress , const char *phone)
{
Person::name = new (char[strlen(name)]);
Person::adress = new (char[strlen(adress)]);
Person::phone = new (char[strlen(phone)]);
setName(name);
setAdress(adress);
setPhone(phone);
cout << "general constructor called; object created, allocated " << sizeof(this->name) << "+" << sizeof(this->adress) << "+" << sizeof(this->phone) << "bytes" << endl;
};
Person::Person(Person const &other)
{
Person::name = new (char[strlen(other.getName())]);
Person::adress = new (char[strlen(other.getAdress())]);
Person::phone = new (char[strlen(other.getPhone())]);
setName(other.getName());
setAdress(other.getAdress());
setPhone(other.getPhone());
cout << "copy constructor called; object created, allocated " << sizeof(name) << "+" << sizeof(adress) << "+" << sizeof(phone) << "bytes" << endl;
};
Person::~Person()
{
delete [] name;
delete [] adress;
delete [] phone;
cout << "destructor called; object removed" << endl;
};
我尝试通过创建一个具有给定参数字符串长度的 C 字符串来节省内存。
认为 C 字符串是一个字符数组,节省字符会导致节省内存,例如“John”的 C 字符串比“Jonathan”的 C 字符串占用更少的内存。
所以现在我不确定我是否理解了 C 字符串或字符数组的错误概念,或者我的实现有问题。
在我的 main 中,我创建了以下对象:
int main()
{
Person t;
t.printPerson();
cout << "size of t: " << sizeof(t) << endl;
Person p("John", "some street", "0736182");
p.printPerson();
cout << "size of p: " << sizeof(p) << endl;
Person x(p);
x.printPerson();
cout << "size of x: " << sizeof(x) << endl;
Person y("Jonathan", "Lancaster Ave 53", "3584695364");
y.printPerson();
cout << "size of y: " << sizeof(y) << endl;
cin.get();
};
但我总是得到每个对象的大小为 24,因此每个成员变量的大小为 8。这是为什么?
提前致谢。