【问题标题】:C++ Vector class as a member in other classC++ Vector 类作为其他类的成员
【发布时间】:2009-10-13 21:50:49
【问题描述】:

请给我这个代码,它给了我很多错误:

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

谁能告诉我这有什么问题?

【问题讨论】:

  • 并非没有错误信息,通常...
  • 发布更多细节、错误消息、更多代码等
  • 你的意思是std::vector吗?每次调用 GetWeight() 时是否要返回整个 verctor 的副本?
  • 为了社区,如果您接受了最佳答案(对于这个问题和您的其他问题),这将很有帮助。

标签: c++ vector


【解决方案1】:

是:

#include <vector>

您使用尖括号是因为它是 standard library, "" 的一部分,只是让编译器先在其他目录中查找,这会不必要地慢。它位于命名空间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-correct:

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

【讨论】:

  • @ChrisW 通常是个坏主意,另一个库中可能有一个矢量类。
  • @ChrisW 我相信你知道,但为了作者的缘故,你不应该在标题中包含所有的std::。要么在#include 语句之后执行using std::vector,要么每次都将其引用为std::vector&lt;T&gt;
  • @GMan,使用“vector”而不是 只会减慢预处理器的速度。使用引号而不是尖括号只是告诉编译器首先在当前目录中查找,如果没有找到,则在适当的包含目录中查找
  • 对,这就是为什么它应该是。也许我会说得更清楚。
【解决方案2】:

首先,#include &lt;vector&gt;。注意尖括号。

其次,它是“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;
}

【讨论】:

    【解决方案3】:
    #ifndef Neuron_h
    #define Neuron_h
    #include "vector"
    
    using std::vector;
    
    class Neuron
    {
    private:
     vector<double>lstWeights;
    public:
     vector<double> GetWeight();
    
    };
    #endif
    

    试试看

    【讨论】:

    • 这仍然行不通,除非 OP 在同一目录中有一个名为“vector”的库。他的意思可能是#include &lt;vector&gt;
    【解决方案4】:

    尝试将vector 替换为std::vector,嗯:

    std::vector<double> lstWeights;
    

    问题在于标准容器位于标准命名空间中,因此您必须以某种方式让编译器知道您想使用标准命名空间的向量版本;您可以通过几种方式之一来执行此操作,std::vector 是最明确的。

    【讨论】:

      【解决方案5】:

      在vector&lt;double&gt; 前加上std::,例如std::vector&lt;double&gt;,应该做的工作。

      【讨论】:

        猜你喜欢
        • 2012-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-02
        • 2012-04-04
        • 1970-01-01
        • 2012-02-18
        相关资源
        最近更新 更多