使用循环范围:参数太少,无法调用函数,单参数';a';未指定 我是C++初学者,我是Bjarne Stroustrup的C++程序设计语言第四的参数化类型。p>
本章试图说明的是在用户定义的类型使用循环范围:参数太少,无法调用函数,单参数';a';未指定 我是C++初学者,我是Bjarne Stroustrup的C++程序设计语言第四的参数化类型。p>,c++,c++11,vector,parameterized-types,C++,C++11,Vector,Parameterized Types,本章试图说明的是在用户定义的类型Vector中定义begin()和end()函数,以便支持循环的范围(即for(auto&s:vs)) 定义begin()和end()函数之后。我得到的错误是函数调用的参数太少,在我使用它们时未指定单个参数“a” 版本1 文本中确实有这样的内容: 在user.cpp中: void f2(const Vector<string> & vs) { for (auto& s: vs) //member functio
Vector
中定义begin()
和end()
函数,以便支持循环的范围(即for(auto&
s:vs
)
)
定义begin()
和end()函数之后。我得到的错误是函数调用的参数太少,在我使用它们时未指定单个参数“a”
版本1
文本中确实有这样的内容:
在user.cpp中:
void f2(const Vector<string> & vs)
{
for (auto& s: vs) //member function 'begin' not viable: 'this' argument has type 'const Vecto<Std::__1::basic_string<char> >
cout << s << '\n';
}
#include "Vector.h"
void f2(Vector<string> & vs)
{
for (auto& s: vs) //too few arguments to function call, single argument 'a' was not specified
cout << s << '\n';
}
在Vector.h中:
template<typename T>
class Vector{
public:
const T* begin(Vector<T>& a);
const T* end(Vector<T>& b);
};
template<typename T>
class Vector{
public:
const T* begin(Vector<T>& a);
const T* end(Vector<T>& b);
};
模板
类向量{
公众:
常数T*begin(向量&a);
常数T*end(矢量和b);
};
在Vector.cpp中:
#include "Vector.h" //get the interface
//To support the range-for loop for our Vector, we must define suitable begin() and end() functions:
template <typename T>
const T* Vector<T>::begin(Vector<T>& x)
{
return & x[0];
}
template <typename T>
const T* Vector<T>::end(Vector<T>& x)
{
return x.begin()+x.size(); //pointer to one past last element.
}
#include "Vector.h" //get the interface
//To support the range-for loop for our Vector, we must define suitable begin() and end() functions:
template <typename T>
const T* Vector<T>::begin(Vector<T>& x)
{
return & x[0];
}
template <typename T>
const T* Vector<T>::end(Vector<T>& x)
{
return x.begin()+x.size(); //pointer to one past last element.
}
#包括“Vector.h”//获取接口
//为了支持向量的循环范围,我们必须定义合适的begin()和end()函数:
样板
常量T*向量::开始(向量和x)
{
返回&x[0];
}
样板
常量T*向量::结束(向量和x)
{
返回x.begin()+x.size();//指向最后一个元素的指针。
}
我已经包括了我认为最关键的部分代码,否则,完整的代码是可用的
因此,我继续并标记函数const
您没有标记成员函数const
。除此之外,它们应该是无参数的。为此,你需要
const T* begin() const;
^^^^^
请注意,您需要使实现在头文件中可用,而不是在单独的.cpp
文件中可用(除非您在头的底部包含该实现,并确保没有人试图编译它)。提供非常量重载也是有意义的
template<typename T>
class Vector{
public:
const T* begin() const {return &x[0]; }
const T* end() const { return &c[0] + size(); }
T* begin() {return &x[0]; }
T* end() { return &c[0] + size(); }
size_t size() const { /* return the size */ }
};
模板
类向量{
公众:
常量T*begin()常量{return&x[0];}
常量T*end()常量{return&c[0]+size();}
T*begin(){return&x[0];}
T*end(){return&c[0]+size();}
size\u t size()常量{/*返回大小*/}
};
您有两个不同的问题。第一个常量是因为begin
和end
函数没有标记为const
,这使得它们不能在常量对象上调用。将声明和定义更改为
const T* begin(Vector<T>& a) const;
const T* end(Vector<T>& b) const;
对end
功能执行相同的操作
template <typename T>
const T* Vector<T>::begin() const
{
return &yourInternalVectorVariable[0];
}