簡體   English   中英

使用類構造函數初始化類對象的指針?

[英]pointer to class objects initialization with class constructor?

// pointer to classes example
// runs with no problem
#include <iostream>
using namespace std;

class Rectangle {
  int width, height;
public:
  Rectangle(int x, int y) : width(x), height(y) {}
  int area(void) { return width * height; }
};


int main() {
  Rectangle obj (3, 4);
  Rectangle * foo, * bar, * baz;
  foo = &obj;
  bar = new Rectangle (5, 6);
  baz = new Rectangle[2] { {2,5}, {3,6} };
  cout << "obj's area: " << obj.area() << '\n';
  cout << "*foo's area: " << foo->area() << '\n';
  cout << "*bar's area: " << bar->area() << '\n';
  cout << "baz[0]'s area:" << baz[0].area() << '\n';
  cout << "baz[1]'s area:" << baz[1].area() << '\n';       
  delete bar;
  delete[] baz;
  return 0;
}   

我有點(沒有雙關語)在這里對這行代碼感到困惑:

baz = new Rectangle[2] {{2,5}, {3,6}};

我見過的代碼如下:

int *foo = new int[3] {1,2,3};

而且我完全理解它。 但這里{{2,5}, {3,6}}的語法是什么? 如何初始化類對象數組? 我搜索了許多在線c ++參考文獻但沒有任何線索。

只需使用初始化列表填充數組中的兩個矩形。

考慮到:

{2,5}, {3,6}

只需調用Rectangle {2,5},Rectangle {3,6}。

Rectangle構造函數有兩個int 如果你看一下Rectangle obj (3, 4); 這也可以是Rectangle obj {3, 4};

(請注意,這僅適用於C ++ 11及更高版本)

baz = new Rectangle[2] { {2,5}, {3,6} };

此語法稱為列表初始化

列表初始化聚合(如數組)會導致聚合初始化 (不出所料),它將對每個元素執行復制初始化 ; 由於這里的初始化器是列表本身,因此導致復制列表初始化

列表初始化(非聚合)類時,編譯器會查找構造函數並選擇最佳匹配。 如果所選構造函數需要對任何參數進行縮小轉換(例如double - > int ),或者它是explicit構造函數,則此時會出現錯誤,因為copy-list-initialization是一種復制形式 - 初始化 ; 只有直接初始化 ,如Rectangle r{2, 5}; 可以使用explicit構造函數(雖然縮小轉換仍然是一個錯誤)。

使用C ++ 11,可以使用{x, y, z}初始化對象實例。 例如:

struct P2d {
    double x, y;
};

void foo(P2d p);

void bar() {
    foo({10, 20}); // Compiles fine
}

將它用於數組是可以的,對於簡單的情況也是如此。 在更復雜的情況下,它只會增加混亂,因為您只看到了值,但您不知道這些值的用途。

這就像使用API​​一樣

 createWindow(0, 0, true, NULL, NULL, 1, NULL, false);

這些價值觀是什么?

只是不要過度使用新的大括號初始化...有些情況下它太棒了:

// C++03
std::vector<int> list_of_values() {
    std::vector<int> result;
    result.push_back(1);
    result.push_back(2);
    result.push_back(3);
    return result;
}

// C++11
std::vector<int> list_of_values() {
    return {1, 2, 3};
}

但有些情況會讓事情變得更糟:

{Rect(2, 3), Rect(4, 5)}

實際上比... 更具可讀性

{{2, 3}, {4, 5}}

(請記住,在編寫代碼時, 閱讀代碼時的輕松程度比輕松程度要輕松得多...大多數代碼行寫入一次並多次讀取)

baz = new Rectangle [2] {{2,5},{3,6}};

是不可編輯的。

甚至,

int * abc = new int[3] {1,2,3} ;

是不可編輯的。

如果您想使用非默認構造函數創建一個Rectangle類數組,請執行以下操作:

  Rectangle baz[] = { Rectangle(2,5) ,  Rectangle(3,6) };

如果不清楚,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM