Re: [問題] 動態宣告class的array並使用constructor
最近在讀Effective C++
期中Item 16:Use the same form in corresponding uses of new and delete.
有個例子給你參考
不過我還是不懂你為何不想用vector就是了@@
typedef std::string AddressLines[4]; // a person's address has 4 lines,
// each of which is a string
std::string *pal = new AddressLines; // note that "new AddressLines"
// returns a string*, just like
// "new string[4]" would
delete pal; // undefined!
delete [] pal; // fine
To avoid such confusion, abstain from typedefs for array types.
That's easy, because the standard C++ library includes
string and vector, and those templates reduce the need for dynamically
allocated arrays to nearly zero. Here, for example, AddressLines could
be defined to be a vector of strings, i.e., the type vector<string>.
※ 引述《musicJD (J.D.)》之銘言:
: 開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
: Linux
: 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
: none
: 問題(Question):
: 我想要動態宣告object的array 該array 共n個object
: 然後每一個object的constructor再動態宣告一個int array
: 該array 共m個int
: class myclass
: {
: public:
: int* array;
: myclass(int n);
: };
: myclass::myclass(int n)
: {
: array = new int[n];
: }
: int main()
: {
: int n = 7;
: int m = 13;
: myclass *x;
: //打 x = new myclass[n](m); 不對
: //打 x = new myclass(m)[n]; 也不對
: }
: 請問要怎麼做?
: 不想用vector...
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.113.242.67
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 3 篇):