新开博客,没什么好写的,先放一篇以前整理的东西上来。
零:直接声明一个对象就不讲了
一:指针对象
<span style="white-space:pre"> </span>Book *aBook = nullptr;
aBook = new Book("C++", "Gaddis", 400);
cout<<aBook->toString()<<endl;
delete aBook;
二:指针指向一个储存Book类对象的数组,该数组在Stack中,三个对象在Heap中,数组中储存三个对象
Book *books = nullptr;
int capacity = 3;
int nrOfBooks = 0;
books = new Book[capacity];
books[nrOfBooks++] = Book("C++", "Gaddis", 400);//后加
books[nrOfBooks].setTitle("Java");
books[nrOfBooks].setAuthor("Sawitch");
books[nrOfBooks].setPrice(500);
nrOfBooks++;
for (int i=0; i<capacity; i++)
{
cout<<books[i].toString()<<endl;
}
system("pause");
delete [] books; //compare delete and delete[],the delete just delete books[0],but delete []can delete all objects
三.声明数组储存3个指针对象,数组在Stack中,对象在Heap中
(与二的区别在于,三中的对象为指针对像,二中声明的是三个对象,而三中声明的是3个指针)
const int CAPACITY = 3;
Book *books[CAPACITY] = {nullptr, nullptr, nullptr};
books[2] = new Book("C++", "Gaddis", 400);
books[0] = new Book("Java", "Sawitch", 500);
for (int i=0; i<CAPACITY; i++)
{
if (books[i] != nullptr)
{
cout<<books[i]->toString()<<endl;
}
}
for (int i=0; i<CAPACITY; i++)
{
if (books[i] != nullptr)
{
delete books[i];
}
}
四.声明一个双指针的数组对象,声明的数组在heap中,对象也在heap中
Book **books = nullptr;
int capacity = 3;
int nrOFBooks = 0;
string title;
string author;
int price;
books = new Book*[capacity];
for (int i=0; i<capacity; i++)
{
books[i] = nullptr;
}
books[nrOFBooks++] = new Book("C++", "Gaddis", 400);
for (int i=0; i<2; i++)
{
cout<<"Input the title of the book: ";
getline(cin, title);
cout<<"Input the author of the book: ";
getline(cin, author);
cout<<"Input the price of the book: ";
cin>>price;
cin.ignore();
books[nrOFBooks++] = new Book(title, author, price);
}
cout<<"This is the books in the array: "<<endl;
for (int i=0; i<capacity; i++)
{
cout<<books[i]->toString()<<endl;
}
for (int i=0; i<nrOFBooks; i++)
{
delete books[i]; // deleting Book object
}
delete [] books; // deleting array
return 0;
}