【发布时间】:2014-09-26 06:45:53
【问题描述】:
我是 C++ 初学者,我正在阅读 Bjarne Stroustrup 的C++ 编程语言第 4 版的 3.4.1 Parameterized Types 部分。
本章试图展示的是在用户定义类型Vector 中定义begin() 和end() 函数,以便range-for loop(即for (auto& s: vs支持))。
定义begin() 和end() 函数后。我在使用它们时收到错误too few arguments to function call, single argument 'a' was not specified。
版本 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';
}
Xcode 然后告诉我member function 'begin' not viable: 'this' argument has type 'const Vecto<Std::__1::basic_string<char> >', but function is not marked const.
所以我继续标记函数 const。
在 Vector.h 中:
template<typename T>
class Vector{
public:
const T* begin(Vector<T>& a);
const T* end(Vector<T>& 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.
}
错误仍然存在。
版本 2
接下来我做的是从函数f2() 中删除const。我收到了这个新错误too few arguments to function call, single argument 'a' was not specified。从 Vector.h 和 Vector.cpp 的函数中删除 const 没有任何区别。
在 user.cpp 中:
#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);
};
在 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.
}
我已经包含了我认为最关键的部分代码,否则,可以使用完整代码here。
【问题讨论】:
标签: c++ c++11 vector parameterized-types