簡體   English   中英

Java中這種語法的等效含義是什么?

[英]What is the equivalent of this syntax in Java?

關於如何在c ++和Java之間轉換特定代碼行的一個簡短問題。 我一直在學習有關神經網絡的知識,並且已經開始用我最熟悉的Java語言來編寫自己的語言。 到目前為止,將代碼從C ++轉換為Java一直很簡單,但是我遇到了一個小問題。 我對如何將特定的代碼行轉換為等效的Java感到困惑,並且無法通過搜索找到與此問題相關的任何內容。

原始代碼是:

Struct SNeuron {
   //the number of inputs into the neuron

   int m_NumInputs;
   //the weights for each input
   vector<double> m_vecWeight;
   //ctor
   SNeuron(int NumInputs);
};

我的代碼是:

public class SNeuron {

public int m_NumInputs; // the number of inputs into the neuron
public ArrayList<Double> m_vecWeight = new ArrayList<Double>(); // the weights for each input
// ctor

我的問題是,如何轉換:

SNeuron(int NumInputs);

變成它的Java等效語言? 從我讀過的內容來看,Structs似乎不是Java所使用的功能,因此我只是在努力地了解一下該代碼行在所使用的上下文中實際上是做什么的。

public class SNeuron 
{

// the number of inputs into the neuron

public int m_NumInputs;

// the weights for each input

public List<Double> m_vecWeight = new ArrayList<Double>();

// ctor
SNeuron(int NumInputs) {
   m_NumInputs = NumInputs;
}

給定代碼中的注釋,我很確定等同於:

public class SNeuron {
    public final double[] weights;

    public SNeuron(int numInputs) {
        weights = new double[numInputs];
    }
}

您實際上並不想使用List<Double> ,它會慢得多並且占用更多的內存-這樣的列表中的每個double都會成為具有所有相關開銷的成熟對象。

在C ++中, SNeuron(int NumInputs); 是采用int的構造函數的聲明,它包含在類聲明中。

您不需要在Java中執行此操作-實際上,所有構造函數以及與此相關的所有函數都內聯到類聲明中。 換一種說法

SNeuron(int NumInputs); // within the class declaration
SNeuron::SNeuron(int NumInputs) : m_NumInputs(NumInputs){} // In a translation unit

映射到

SNeuron(int NumInputs) {
   m_NumInputs = NumInputs;
}

但請注意,對Java 字段使用m_是特質的。

暫無
暫無

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

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