首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将C++向量类作为其他类中的成员

将C++向量类作为其他类中的成员
EN

Stack Overflow用户
提问于 2009-10-13 21:50:50
回答 5查看 12.4K关注 0票数 0

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

代码语言:javascript
复制
//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;
}

有人能告诉我它出了什么问题吗?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2009-10-13 21:52:46

它是:

代码语言:javascript
复制
#include <vector>

你使用尖括号是因为它是standard library的一部分,"“只会让编译器首先在其他目录中查找,这是不必要的缓慢。并且它位于命名空间std

代码语言:javascript
复制
std::vector<double>

您需要在正确的名称空间中限定您的向量:

代码语言:javascript
复制
class Neuron
{
private:
 std::vector<double>lstWeights;
public:
 std::vector<double> GetWeight();

};

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

使用typedef的使其更简单:

代码语言:javascript
复制
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

代码语言:javascript
复制
const container_type& GetWeight() const; // const because GetWeight does
                                         // not modify the class
票数 16
EN

Stack Overflow用户

发布于 2009-10-13 21:56:48

首先是#include <vector>。请注意尖括号。

其次,它是'std::vector',而不仅仅是'vector‘(或者使用'using’指令)。

第三,不要通过值返回向量。这是很繁重的,通常是完全不必要的。改为返回常量引用

代码语言:javascript
复制
class Neuron {
private: 
    std::vector<double> lstWeights;
public: 
    const vector<double>& GetWeight() const;
};    

const std::vector<double>& Neuron::GetWeight() const
{ 
  return lstWeights;
}
票数 2
EN

Stack Overflow用户

发布于 2009-10-13 21:53:17

代码语言:javascript
复制
#ifndef Neuron_h
#define Neuron_h
#include "vector"

using std::vector;

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

};
#endif

试试看

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1563124

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档