我为我的String
类声明并实现了一些迭代方法:begin()
,end()
等等......但是当我尝试在测试程序中使用它们时,我得到了未定义的引用对所有人来说。
String.h
:
public:
typedef char* iterator;
typedef const char* const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
iterator begin();
iterator begin() const;
iterator end();
iterator end() const;
const_iterator cbegin();
const_iterator cend();
reverse_iterator rbegin();
reverse_iterator rbegin() const;
reverse_iterator rend();
reverse_iterator rend() const;
const_reverse_iterator crbegin();
const_reverse_iterator crend();
private:
char* string_;
String.cpp
:
inline String::iterator String::begin() {
return string_;
}
inline String::iterator String::begin() const {
return string_;
}
inline String::iterator String::end() {
return string_ + length_ - 1;
}
inline String::iterator String::end() const {
return string_ + length_ - 1;
}
inline String::const_iterator String::cbegin() {
return string_;
}
inline String::const_iterator String::cend() {
return string_ + length_ - 1;
}
inline String::reverse_iterator String::rbegin() {
return reverse_iterator(end());
}
inline String::reverse_iterator String::rbegin() const {
return reverse_iterator(end());
}
inline String::reverse_iterator String::rend() {
return reverse_iterator(begin());
}
inline String::reverse_iterator String::rend() const {
return reverse_iterator(begin());
}
inline String::const_reverse_iterator String::crbegin() {
return reverse_iterator(end());
}
inline String::const_reverse_iterator String::crend() {
return reverse_iterator(begin());
}
有什么问题?
答案 0 :(得分:0)
未定义的参考?但它编译得很好。 我添加了一个构造函数:
String(const char *cc) {
string_ = new char[length_ = strlen(cc) + 1];
strcpy(string_, cc);
}
当然,添加了一个数据成员
int _length;
我的测试程序如下:
String aa(“abc”); String :: iterator itr = aa.begin(); cout&lt;&lt; itr&lt;&lt; ENDL;
打印“abc” 没问题!