[英]how to get the member in C++ struct initialization
struct Test {
int w, h;
int * p;
};
int main(){
Test t {
10,
20,
new int[this->h*this->w]
};
return 0;
}
我只想在初始化中使用 w 和 h,有什么辦法可以得到這個嗎?
首先 - 你應該避免顯式調用new
(和delete
) ,除非在極少數情況下; 這不是其中之一。 使用std::unique_ptr
來保存您分配的 memory (見下文)。
要回答您的問題:您不能將結構/類的成員用作該結構/類的構造函數的 arguments。 從概念上講,arguments 在構造函數運行之前被解析。
但是,您可以編寫命名構造函數:
struct Test {
int w, h;
std::unique_ptr<int[]> p;
static:
Test make(int w, int h) {
return Test{ w, h, std::make_unique<int[]>(w*h) };
}
};
這會讓你寫:
auto my_test = Test::make(w, h);
或者,您可以直接實現一個只需要w
和h
的構造函數:
struct Test {
int w, h;
std::unique_ptr<int[]> p;
Test(int w_, int h_) : w(w_), h(_), p(std::make_unique<int[]>(w_*h_) { }
};
...但是您需要為無參數構造函數和 3 參數構造函數(如果不是其他方法)編寫一些額外的代碼。
如果您為 class 編寫構造函數,則可以利用其成員初始化列表。 特別是,您可以利用“非靜態數據成員按 class 定義中的聲明順序初始化”這一事實。
考慮這個不那么瑣碎的例子
#include <iostream>
#include <stdexcept>
#include <vector>
class Matrix
{
int h_{};
int w_{};
std::vector<int> d_;
public:
Matrix() = default;
Matrix(int h, int w)
: h_{checked_positive(h)}
, w_{checked_positive(w)}
, d_(h_ * w_) // <--
{}
void show() {
std::cout << h_ << ' ' << w_ << ' ' << d_.size() << '\n';
}
private:
int checked_positive(int d) {
if (d < 1)
throw std::runtime_error{"Dimensions must be positive"};
return d;
}
};
int main()
{
Matrix a(3, 4);
a.show();
}
但請注意,一些審閱者可能會發現這種對成員聲明順序的依賴是不必要的,並且會增加可維護性成本。
或者,依賴成員可以默認初始化,然后在構造函數的主體中修改:
class Matrix
{
std::vector<int> d_; // <--
int h_{}, w_{};
public:
Matrix() = default;
Matrix(int h, int w)
: h_{checked_positive(h)}
, w_{checked_positive(w)}
{
d_.resize(h_ * w_); // <--
}
// ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.