簡體   English   中英

C ++ Vector類作為其他類的成員

[英]C++ Vector class as a member in other class

請我有這段代碼,它給了我很多錯誤:

//Neuron.h File
#ifndef Neuron_h
#define Neuron_h
#include "vector"
class Neuron
{
private:
 vector<double>lstWeights;
public:
 vector<double> GetWeight();

};
#endif

//Neuron.cpp File
#include "Neuron.h"
vector<double> Neuron::GetWeight()
{
 return lstWeights;
}

誰能告訴我這是怎么回事?

它的:

#include <vector>

您可以使用尖括號,因為它是標准庫 “”的一部分,只是使編譯器首先在其他目錄中查找,這不必要地很慢。 它位於名稱空間std

std::vector<double>

您需要在正確的名稱空間中限定向量:

class Neuron
{
private:
 std::vector<double>lstWeights;
public:
 std::vector<double> GetWeight();

};

std::vector<double> Neuron::GetWeight()

使用typedef更簡單:

class Neuron
{
public:
    typedef std::vector<double> container_type;

    const container_type& GetWeight(); // return by reference to avoid
                                       // unnecessary copying

private: // most agree private should be at bottom
    container_type lstWeights;
};

const Neuron::container_type& Neuron::GetWeight()
{
 return lstWeights;
}

另外,別忘了是const正確的

const container_type& GetWeight() const; // const because GetWeight does
                                         // not modify the class

首先, #include <vector> 注意尖括號。

其次,它是“ std :: vector”,而不僅僅是“ vector”(或使用“ using”指令)。

第三,不要按值返回向量。 這很重,通常完全沒有必要。 返回一個[const]引用

class Neuron {
private: 
    std::vector<double> lstWeights;
public: 
    const vector<double>& GetWeight() const;
};    

const std::vector<double>& Neuron::GetWeight() const
{ 
  return lstWeights;
}
#ifndef Neuron_h
#define Neuron_h
#include "vector"

using std::vector;

class Neuron
{
private:
 vector<double>lstWeights;
public:
 vector<double> GetWeight();

};
#endif

試試看

嘗試用std::vector替換vector ,例如:

std::vector<double> lstWeights;

問題在於標准容器位於標准名稱空間中,因此您必須以某種方式讓編譯器知道您要使用標准名稱空間的vector版本; 您可以通過以下幾種方法之一進行操作,其中std::vector是最明確的方法。

vector<double>加上std::前綴,例如std::vector<double> ,即可完成工作。

暫無
暫無

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

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