C++ Vector class as a member in other class
Please I have this code which gives me many errors:
//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;
}
Could any one tell me what is wrong with it?
It's:
#include <vector>
You use angle-brackets because it's part of the standard library, "" with just make the compiler look in other directories first, which is unnecessarily slow. And it is located in the namespace std
:
std::vector<double>
You need to qualify your vector in the correct namespace:
class Neuron
{
private:
std::vector<double>lstWeights;
public:
std::vector<double> GetWeight();
};
std::vector<double> Neuron::GetWeight()
Made simpler with typedef's:
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;
}
Also, don't forget to be const-correct:
const container_type& GetWeight() const; // const because GetWeight does
// not modify the class
Firstly, #include <vector>
. Note the angular brackets.
Secondly, it's 'std::vector', not just 'vector' (or use 'using' directive).
Thirdly, don't return vectors by value. This is heavy and usually completely unnecessary. Return a [const] reference instead
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
try that
try replacing vector
with std::vector
, a la:
std::vector<double> lstWeights;
The issue is that the standard containers are in the standard namespace, so you have to somehow let the compiler know that you'd like to use the standard namespace's version of vector; you do that one of several ways, std::vector
being the most explicit.
Prefixing vector<double>
with std::
, e.g. std::vector<double>
, should do the work.
精彩评论