我想你已經在你的生活中做過很多C了。請記住,C++是不同的語言,它恰好與C的大部分語法和它的一些標準庫共享。這意味着C中完美的東西在C++中可能相當醜陋(甚至是危險的)。
隨着中說,讓我們重寫代碼更「C++ - 雜交」的方式:
#include <iostream> // std::cout, std::endl
#include <string> // std::string
struct Rec // typedef is implicit for structs in C++
{
std::string s1; // use std::string instead of char arrays
std::string s2;
std::string s3;
}; // don't forget the semicolon!
int main()
{
Rec * a[10];
a[0] = new Rec; // allocates the right amount of memory, no need to cast
a[0]->s1 = "hello"; // std::sring handles the assignment for you
std::cout << "a[0] = " << a[0]->s1 << std::endl; // use iostreams
delete a[0]; // delete is an operator, not a function, no need for parentheses
getchar(); // warning, this is not portable
return 0;
}
正如你看到的,new
是不是「改善malloc
」。它是類型安全的(不需要強制轉換),使用更安全(它分配所需的確切內存量,不需要sizeof
),它也做一些malloc
不能做的事情:它調用類的構造函數(就像delete
調用析構函數)。
在C++中,如在C中,分配不同於初始化。而在C中你可以只將memset
的塊歸零,在C++中對象構造可能會更復雜一點。因此,你應該從來沒有使用malloc
來創建具有不平凡的構造函數的類的對象(或有沒有不平凡的構造函數的字段 - Rec
就是這種情況)。因爲new
總能正常工作,並具有其他功能,所以無論如何您都應該使用它。
什麼是舊式'typedef struct {...} Rec;'構造? –
@John我發誓,沒有足夠的重點放在C和C++之間的區別。 –
'new'比'malloc'更強大,因此使用它:'a [0] = new Rec();' – AJG85