代码之家  ›  专栏  ›  技术社区  ›  Joseph Oliver

这种语法在Java中的等价物是什么?

  •  -1
  • Joseph Oliver  · 技术社区  · 8 年前

    这是一个关于如何在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等价物?从我所读到的内容来看,结构似乎不是Java使用的功能,所以我只是有点难以理解这行代码在所使用的上下文中到底做了什么。

    3 回复  |  直到 8 年前
        1
  •  1
  •   Ashwel    8 年前
    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;
    }
    
        2
  •  1
  •   xs0    8 年前

    考虑到代码中的注释,我很确定等价物是:

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

    你真的不想使用 List<Double> ,速度会慢得多,占用的内存也会大得多——这样一个列表中的每一个双精度对象都会成为一个具有所有相关开销的成熟对象。

        3
  •  0
  •   Bathsheba    8 年前

    在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;
    }
    

    但请注意,使用 m_ 对于Java 领域 是特殊的。