2016-09-06 85 views
0

我的代碼中存在以下情況,並且不知道它是否顯示了一些錯誤的設計。將此變量傳遞給此類變量的方法

class A 
{ 
public: 
    ... 
    void estimateParameters(const std::vector<double> &data); 
private: 
    B m_algorithm; 
    int m_parameter1; 
    int m_parameter2; 
}; 

void A::estimateParameters(const sdt::vector<double> &data) 
{ 
    m_algorithm.estimate(this, data); // And then m_parameter1 and m_parameter2 are filled 
} 

estimateParameters該實現調用的Bestimate方法,它接收作爲參數的指針this。這聽起來有點奇怪,似乎多餘。我正在使用此方案封裝參數估計A,而不強制用戶在其代碼中手動創建B的實例,然後通過A。這是一種對用戶進行透明參數估計的方法。

這種方案很常見嗎?你認爲這是做這件事的最好方法嗎?任何替代品不多或更清晰?

謝謝

+1

不應該是'm_algorithm.estimate(this,data);'而不是'B.m_algorithm'? – sergej

+0

如果有任何問題,請參考'* this'。 – LogicStuff

+0

對不起,我已將其更改 – Javier

回答

-1

是的,它是傳遞指向對象的好方法。它不是多餘的。

+0

這不提供問題的答案。要批評或要求作者澄清,請在其帖子下方留言。 - [來自評論](/ review/low-quality-posts/13585539) – BWA

+0

@BWA這既不是評論家,也不是要求。這是在帖子末尾提問的回答。 – teivaz

+1

但在這種形式它是評論。 – BWA

1

爲了使這個更清潔,我將參數作爲結構傳遞。沒有必要對B類知道A類的一切

示例代碼

// Struct that class B can use without having to 'know' about class A 
struct EstimateParameters 
{ 
    int m_parameter1; 
    int m_parameter2; 
}; 

class B 
{ 
public: 
    void estimate(const EstimateParameters& estimateParams, const std::vector<double> &data) 
    { 
     /* Use estimate params to act on data. 
      We don't care about the whole of class A, only performing estimates */ 
    } 
}; 

// Class A now composed of EstimateParameters. 
class A 
{ 
public: 
    void estimateParameters(const std::vector<double> &data); 
private: 
    EstimateParameters m_estimateParams; 
    B m_algorithm; 
}; 

// Passing only the private structure of params, not details of the whole of class A. 
void A::estimateParameters(const std::vector<double> &data) 
{ 
    m_algorithm.estimate(m_estimateParams, data); 
} 

編輯這個答案基於有用的意見,謝謝你們!

+0

第1點很清楚。第2點仍然有點難以理解。你能澄清一下嗎?謝謝。 – Javier

+0

將很快上傳一個例子 –

+0

非常感謝 – Javier

1

您的設計讓我想起了Strategy pattern,這個例子對我來說很有意義。

這裏的一個問題是B取決於A。您可以通過引用傳遞參數(而不是this-pointer)來移除此依賴項。

m_algorithm.estimate(m_parameter1, m_parameter2, data); 

此外,定義一個Parameters類(或結構體)也許有意義。

struct Parameters { 
    int m_parameter1; 
    int m_parameter2; 
} 

class A { 
public: 
    void estimateParameters(const std::vector<double>& data); 
private: 
    B m_algorithm; 
    Parameters m_parameters; 
}; 

void A::estimateParameters(const std::vector<double>& data) { 
    m_algorithm.estimate(m_parameters, data); 
} 

void B::estimate(Parameters& parameters, const std::vector<double>& data) { ... } 
+0

是的,但在實際情況下,不僅有兩個參數,而且還有很多東西。因此,我想你的參數類的建議。 – Javier

+0

@Javier對,請參閱編輯答案。 – sergej