簡體   English   中英

通過C ++中的指針將子對象值傳遞給被調用者類

[英]passing a child object value to callee class through pointer in C++

原始代碼似乎引起很多混亂,因此我刪除並添加了其他說明性代碼。 希望它不會造成同樣的混亂。

將此視為Main calss考量( something like manager class

HPP:

 private: std::vector<int>* _cache;

CPP:

 whatever* whatever::somefunction(const String& nothing)
    {
        const auto newWhatever = new whatever{nothing, _cache};
        return newWhatever; // not important
    }

Other Class (完成某些工作並返回結果的類)

HPP:

private: std::Vector<int> _cache;

CPP:

     class OtherClass
{
    std::vector* _value;
    std::vector _result;
public:
    OtherClass(const string& nothing, std::vector<int>* cache) : _value{cache}

    void calculateresult()
    {
      *_value = _result;
      }
}

returning value from the method is impossible as per the original setup

我想將在OtherClass獲得的結果捕獲到Main class的指針中。

目的是: OtherClass是臨時的,它將每隔10秒銷毀並重新創建一次。 因此,我需要存儲此OtherClass的結果,並將其用於下一個實例化。 如您所見,此OtherClass的實例化將在Main class ,就像管理器一樣。

當我調試時,我確實看到為_value分配了一個地址,並且取消引用它可能不起作用,我不知道。

但是它在賦值期間失敗,即*_value = _result;

左為T = QVector *,右為QVector。

代碼中的異常: qvector.h

template <typename T>
QVector<T> &QVector<T>::operator=(const QVector<T> &v)
{
    if (v.d != d) {
        QVector<T> tmp(v);
        tmp.swap(*this);
    }
    return *this;
}

很簡單:

class Child
{
    int m_Data = 0;

public:
    Child(int Data) : m_Data(Data) {};

    int doSomething()
    {
        // Do something ("Child calculation") , for example:
        int a = 0, b = 0, c = 0, d = 0, e = 0, f = m_Data, r = 0;
        r = a * b * c * d * e * f + a * b * c + f + 5;

        return r;
    }
};

采用:

Child Chl(5);

int Result = Chl.doSomething(); // Result is 10

-

如果您更喜歡使用指針:...您寫道:“將值從Parent傳遞給孩子作為指針,並使孩子計算結果存儲在該Parent值指針所指向的位置。”:

class Child
{
    int * m_pData = nullptr;

public:
    Child(int * pData) : m_pData(pData) {};

    void doSomething()
    {
        // Do something ("Child calculation") , for example:
        int a = 0, b = 0, c = 0, d = 0, e = 0, f = *m_Data, r = 0;
        r = a * b * c * d * e * f + a * b * c + f + 5; 

        *m_pData = r; // "store in the location pointed"
    }
};

采用:

int Data = 5; // "A value from Parent"

Child Chl(&Data); // "To the Child, as a pointer"

Chl.doSomething(); // Data is 10

-

  • 它可以是std::vector而不是int

我認為您想要的是(請注意*為Localvalue):

class Child
{
    public:
        Child (int* value) : Localvalue{value};
        int* Localvalue;
        int Resultvalue;
        void doSomething() {
            if (Localvalue != nullptr) 
                *Localvalue = Resulvalue; 
        }
};

話雖這么說,這是一個不好的設置。 子級要求所有者確保所傳遞的指針在Child實例生命期內一直有效。

您可以使用shared_ptr<int>對其進行改進。 或者按照您問題上的其他建議從doSomething()返回值。 即使您現在返回一個向量,由於返回值的優化,也應該不會有性能問題。

暫無
暫無

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

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