破译c++代码:结构中的函数与结构同名

Deciphering C++ code: function in struct with same name as the struct

本文关键字:结构 函数 c++ 代码 破译      更新时间:2023-10-16

我正在尝试学习编程。我从ai-junkie.com上得到这个代码。我不明白每个结构体的最后几行

  1. SNeuron (int NumInputs)
  2. SNeuronLayer(int NumNeurons, int NumInputsPerNeuron).

这样做的目的是什么?有人愿意教基础c++吗?

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);
};
struct SNeuronLayer {
    //the number of neurons in this layer
    int m_NumNeurons;
    //the layer of neurons
    vector<SNeuron> m_vecNeurons;
    SNeuronLayer(int NumNeurons, int NumInputsPerNeuron);
};

这是一个构造函数。有人给它加了一个毫无意义的评论ctor。它允许您使用如下代码实例化SNeuron的实例

SNeuron sn(5);

这有助于程序的稳定性。在C语言中,您必须在实例化结构的实例后自己填充结构字段。这会使结构处于不明确的状态。在c++中,实例可以一步完成。

请记住,在c++中,structclass完全相同:除了struct中所有成员函数和成员数据默认为public(而在class中它们默认为private)。

这是struct SNeuron接受int的C-tor。

在c++中,struct就是包含所有成员publicclass。像任何class一样,它可以有C -tor, d- tor和其他c++元素。