【发布时间】:2014-01-10 10:27:43
【问题描述】:
这是C++ Primer 5th Edition中的一个练习:
练习 14.7:为你定义一个输出运算符 String 类你 为第 13.5 节(第 531 页)中的练习而写。(第 558 页)
我为之前的练习写的string.h:
/**
* @brief std::string like class without template
*
* design:
*
* [0][1][2][3][unconstructed chars][unallocated memory]
* ^ ^ ^
* elements first_free cap
*/
class String
{
friend std::ostream& operator <<(std::ostream& os, const String& s);
public:
//! default constructor
String();
//! constructor taking C-style string i.e. a char array terminated with'\0'.
explicit String(const char * const c);
//! copy constructor
explicit String(const String& s);
//! move constructor --07.Jan.2014
String(String&& s) noexcept;
//! operator =
String& operator = (const String& rhs);
//! move operator = --07.Jan.2014
String& operator = (String&& rhs) noexcept;
//! destructor
~String();
//! members
char* begin() const { return elements; }
char* end() const { return first_free; }
std::size_t size() const {return first_free - elements; }
std::size_t capacity() const {return cap - elements; }
private:
//! data members
char* elements;
char* first_free;
char* cap;
std::allocator<char> alloc;
//! utillities for big 3
void free();
};
std::ostream&
operator << (std::ostream& os, const String& s);
部分string.cpp:
//! constructor taking C-style string i.e. a char array terminated with'\0'.
String::String(const char * const c)
{
auto p = c;
char* newData = alloc.allocate(sizeof(p));
std::uninitialized_copy(p, (p + sizeof(p)), newData);
//! build the data structure
elements = newData;
cap = first_free = newData + sizeof(c);
}
std::ostream &operator <<(std::ostream &os, const String &s)
{
std::for_each(&s.elements, &s.first_free, [&](const char* p){
os << *p;
});
return os;
}
main.cpp:
#include "string.h"
#include <iostream>
int main()
{
String s("1234");
std::cout << s <<"\n";
return 0;
}
输出:
1
Press <RETURN> to close this window...
为什么输出是这样的?为什么不1234?
【问题讨论】:
标签: c++ c++11 stl lambda operator-overloading