簡體   English   中英

將向量從一類傳遞到另一類作為對象

[英]passing vector from one class to other as object

我有兩個類NetGA ,我想通過main將向量從GA傳遞到Net 考慮以下代碼。

class GA {
    inline vector <double> get_chromosome(int i) { 
        return population[i]; 
    }
}

class Net {
    int counter;
    Net::setWeights(vector <double> &wts){
        inpHidd = wts[counter];
    }
}

main(){
    net.setWeights( g.get_chromosome(chromo) );
}

錯誤是:

Network.h:43:8: note: void Network::setWeights(std::vector<double>&)
   void setWeights ( vector <double> &wts );
        ^
Network.h:43:8: note:   no known conversion for argument 1 from ‘std::vector<double>’ to ‘std::vector<double>&’

任何想法?

這很簡單:根據標准,只有const引用可以綁定到臨時對象。

g.get_chromosome(chromo)返回一個臨時值,而Net::setWeights(vector <double> &wts)嘗試使用常規引用將其綁定到其中。

Network::setWeights(std::vector<double>& wts)應該是Network::setWeights(const std::vector<double>& wts)如果你不打算改變向量,或者Network::setWeights(std::vector<double> wts)如果這樣做)。

最后一種選擇是移動矢量,在這種情況下,您應該使用move語義

如果不知道如何宣布人口,我會說要改變返回人口[i]; 歸國人口; 在get_chromosome中

我創建了答案。 實際上,問題出在Net的接收端。 你不需要那個 如果您不更改向量。 @Dvid是正確的。

考慮以下示例:

#include <iostream>
using namespace std; 
void addone (int &x){
    x = x + 10; 
}

void addtwo(int x){
    x = x + 10; 
}

int main (){    
int x = 10; 
addone(x);
cout<<x; 
int y = 10;
addtwo(y);
cout<<endl<<y;
}

輸出為:

20
10

暫無
暫無

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

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