It's an exercise from C++ Primer 5th Edition:
Exercise 14.7: Define an output operator for you String class you
wrote for the exercises in ยง 13.5 (p. 531).(Page 558)
The string.h I wrote for previous exercises:
/**
* #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);
Part of the 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;
}
Output:
1
Press <RETURN> to close this window...
Why is the output like so? why not 1234?
Probably because elements points to an array of char, so each element is a char, not a char*.
You also need to drop the & in front of s.elements and s.first_free, because you are interested in the addresses the pointers point to, not the addresses of the pointers themselves.
So, this code would work:
std::for_each(s.elements, s.first_free, [&](char p){
os << p;
});
As mentioned by #TemplateRex in comments, it would be both cleaner and more idiomatic to use the begin() and end() member functions:
std::for_each(s.begin(), s.end(), [&](char p){ os << p; });
sizeof(pointer) where pointer is a char const* does not return the length of an array. You make this mistake multiple times. Use strlen instead. This is hidden because your string is 4 char long, and on a 32 bit system sizeof(ptr) is 4.
Next &first_free and similar in your for_each should be just first_free.
Next your lambda should take char not char*s. Then the output should be << p not << *p.
You should create both const and non-const begin and end. const returns char const *, while non const returns char* -- containers that logically own their underlying data should use const that way for iteration.
Next replace your for_eaxh to use begin() and end() like for_each( x.begin(), x.end(), ... -- no need to redo what begin and end do. In C++11 you can even use a ranged based for:
for(char c : s ) {
std::cout << c
}
instead of for_each.
Related
hello i have problem in my school c++ lab, my bool operator > should be return true if lhs is greater than rhs, however it always return false. i try print out lhs.tostring(), it show the number correctly.
my lhs and rhs is a string value.
due to some confidence restrict from my school work, i am not allow to post all the function of my work.
Updated information: ithis lab only can use c++14 and can't include any additional lib. The int value is written in string, and need to compare which is bigger. Assuming there is no negative and any letter other than number
some part of my header file
#include <cstring>
#include <iostream>
namespace CS170
{
class BigNum
{
public:
/* Constructor of BigNum object.
Takes in a character string and
constructs a BigNum */
BigNum(const char * rhs = "0");
/* one of rule of 3 need destructor */
~BigNum();
/* Return a character pointer pointing
to the start of the array representing the big num */
const char * toString() const;
/* Return how many digits the number has */
size_t getNumDigits() const;
BigNum & operator =(const BigNum & rhs);
private:
size_t len;
char* num;
};
}
bool operator >(const CS170::BigNum &lhs, const CS170::BigNum &rhs);
cpp
namespace CS170
{
BigNum::BigNum(const char * rhs )
:len{strlen(rhs)}, num{new char[len+1]}
{
strcpy(num,rhs);
}
BigNum::~BigNum()
{
}
const char * BigNum::toString() const
{
return num;
}
size_t BigNum::getNumDigits() const
{
return len;
}
}
bool operator >(const CS170::BigNum &lhs, const CS170::BigNum &rhs)
{
CS170::BigNum left_value{lhs};
CS170::BigNum right_value{rhs};
std::cout << std::endl;
std::cout << left_value.toString() << " " << right_value.toString() <<
std::endl;
/*this don't work for comparing**/
if(left_value.toString() > right_value.toString())
return true;
else
return false;
}
left_value.toString() > right_value.toString()
This does not do what you think it does. toString() returns a const char*, a pointer to some data. Formally the behaviour of > in your case is undefined since the pointers are not part of the same array, and even if they were, the result would not depend on the string contents.
To check the lexicogrammatical order of strings, you should use the right tool for it, for instance std::string::operator>:
std::string lhs_string{left_value.toString()};
std::string rhs_string{rght_value.toString()};
if (lhs_string > rhs_string)
// ...
// note: here you could simply do return lhs_string > rhs_string;
If you're using a recent compiler and C++17 is an option, you could also use those tools without copying data around:
#include <string_view>
const char* lhs = "programming";
const char* rhs = "language";
std::string_view lhs_string{lhs};
std::string_view rhs_string{rhs};
lhs_string>rhs_string // lexicogrammatical order
live demo
const char* cannot be compared in the way you are trying to. You have to use strcmp. Example usage would look like:
if (strcmp(left_value.toString(), right_value.toString()) > 0)
{
return true;
}
The last part of the function could even be simplified to:
return strcmp(left_value.toString(), right_value.toString()) > 0;
is nearly there but i don't work if compare 11 > 2, as is still read only the first string.
bool operator >(const CS170::BigNum &lhs, const CS170::BigNum &rhs)
{
CS170::BigNum left_data{lhs};
CS170::BigNum right_data{rhs};
int result = strncmp(left_data.toString(), right_data.toString(),20);
return result > 0;
}
I've been writing my own String class and I am not sure how to write operator+ correctly considering I could pass rvalues into it.I think I should have the following 3 non-member functions
String operator+(String &&lhs, String &&rhs);
String operator+(String& lhs,String&&rhs);
String operator+(String&&lhs,String&rhs);
However I am not sure how to implement them. Any help would be appreciated.
First, make sure to define copy and move constructors in your String class:
class String
{
private:
char *m_data;
std::size_t m_length;
...
public:
String();
String(const String &src);
String(String &&src);
~String();
...
};
String::String() :
m_data(nullptr),
m_length(0)
{
}
String(const String &src) :
m_data(new char[src.m_length+1]),
m_length(src.m_length)
{
std::copy_n(src.m_data, m_length, m_data);
m_data[m_length] = 0;
}
String(String &&src) :
m_data(nullptr),
m_length(0)
{
std::swap(m_data, src.m_data);
std::swap(m_length, src.m_length);
}
String::~String()
{
delete[] m_data;
}
Then define operator+ and operator+= for the class:
class String
{
public:
...
String& operator+=(const String &rhs);
...
friend String operator+(String lhs, const String &rhs)
{
lhs += rhs;
return lhs;
}
};
String& String::operator+=(const String &rhs)
{
String tmp;
tmp.m_length = m_length + rhs.m_length;
tmp.m_data = new char[tmp.m_length+1];
std:copy_n(m_data, m_length, tmp.m_data);
std:copy_n(rhs.m_data, rhs.m_length, tmp.m_data + m_length);
tmp.m_data[tmp.m_length] = 0;
std::swap(m_data, tmp.m_data);
std::swap(m_length, tmp.m_length);
return *this;
}
By taking a const String & as input on the right side, that will handle both lvalue and rvalue inputs.
For operator+, the left-hand side is taken by value so the compiler can decide the best constructor to use based on whether the input is an lvalue (copy) or rvalue (move).
Alternatively, you can implement it to take const String & on the left side so it still handles lvalues and rvalues, but then you have to implement it similar to how operator+= is implemented to avoid the extra allocation of copying lhs before concatenating onto it:
friend String operator+(const String &lhs, const String &rhs)
{
/*
String tmp(lhs);
tmp += rhs;
return tmp;
*/
String tmp;
tmp.m_length = lhs.m_length + rhs.m_length;
tmp.m_data = new char[tmp.m_length+1];
std:copy_n(lhs.m_data, lhs.m_length, tmp.m_data);
std:copy_n(rhs.m_data, rhs.m_length, tmp.m_data + lhs.m_length);
tmp.m_data[tmp.m_length] = 0;
return tmp;
}
Either way, you should also define a conversion constructor and operator+ for const char * input as well:
class String
{
public:
...
String(const char *src);
...
friend String operator+(const char *lhs, const String &rhs)
{
return String(lhs) + rhs;
/* or:
std::size_t len = std::strlen(lhs);
String tmp;
tmp.m_length = len + rhs.m_length;
tmp.m_data = new char[tmp.m_length+1];
std:copy_n(lhs, len, tmp.m_data);
std:copy_n(rhs.m_data, rhs.m_length, tmp.m_data + len);
tmp.m_data[tmp.m_length] = 0;
return tmp;
*/
}
...
};
String::String(const char *src) :
m_data(nullptr),
m_length(std::strlen(src))
{
m_data = new char[m_length+1];
std::copy_n(src, m_length, m_data);
m_data[m_length] = 0;
}
This will allow concatenating String objects with string literals (String + "literal", "literal" + String, String += "literal", etc).
See operator overloading on cppreference.com for more details.
The way I usually do it is like this:
class foo
{
...
public:
...
foo&& operator +(foo const & other) &&;
foo&& operator +(foo && other) const &;
foo&& operator +(foo && other) &&;
foo operator +(foo const & other) const &;
};
Not sure if Microsoft supports this but this is a good way to do this in more recent standards. Try clang if msvc wont let you.
The advantages of doing it this way are that you get very fine levels of control over the method used. These 4 operations can also be defined outside of the class if needed. But you'll always want 4 for the 4 possibilities of r-value/l-value combinations.
Also, you generally want to qualify l-values as const to indicate that they are not modified.
Simply defining a copy/move constructor is not usually an efficient solution to this problem. You will need a good understanding of how rvalue references work to implement this efficiently.
Just started learning C++ recently and I'm attempting to make my own string class from scratch. I'm currently working on concatenating strings by overloading += and + operators. After reading this article, basic-rules-of-operator-overloading, I have come up with the following implementation;
String & String::operator+=(const String &o)
{
char * newBuffer = new char[this->size() + o.size() - 1];
//copy over 'this' string to the new buffer
int index = 0;
while (this->at(index) != 0x0)
{
*(newBuffer + index) = this->at(index);
index++;
}
//copy over the param string into the buffer with the offset
//of the length of the string that's allready in the buffer
int secondIndex = 0;
while (o.at(secondIndex) != 0x0)
{
*(newBuffer + index + secondIndex) = o.at(secondIndex);
secondIndex++;
}
//include the trailing null
*(newBuffer + index + secondIndex) = 0x0;
//de-allocate the current string buffer and replace it with newBuffer
delete[] this->s;
this->s = newBuffer;
this->n = index + secondIndex;
return *this;
}
inline String operator+(String lhs, const String &rhs)
{
lhs += rhs;
return lhs;
}
However, the compiler will not recognise the + overload! It does work if I place the function in the main test file (where I am calling the method) but not if I place it in my String.cpp file where all my other methods are located.
Here is my String.h file if you need it;
#include <iostream>
class String
{
public:
String(const char * s);
String(const String &o);
int size() const;
char at(int i) const;
String &operator+=(const String &o);
private:
char * s;
int n;
//needs to be a friend function defined OUTSIDE of the class as when using
//ostream << String you do not have access to the ostream so they can't be
//member operators
friend std::ostream & operator<<(std::ostream &os, const String &o);
};
Thanks for any help!
(also, anything you think I can improve on in regards to my implementation would be graciously received)
Well everyone already explained, so it should be as simple as just adding the forward declaration to the end of your .h file like this:
#include <iostream>
class String
{
public:
String(const char * s);
String(const String &o);
int size() const;
char at(int i) const;
String &operator+=(const String &o);
private:
char * s;
int n;
//needs to be a friend function defined OUTSIDE of the class as when using
//ostream << String you do not have access to the ostream so they can't be
//member operators
friend std::ostream & operator<<(std::ostream &os, const String &o);
};
//forward declaration
String operator+(String lhs, const String &rhs);
The forward declaration just tells the compiler to look for a function with that signature. When it doesn't find it in your current .cpp file it looks up on the other .cpp files. I hope this helps!
Here is an exercise from C++ Primer 5th Edition:
Exercise 14.26: Define subscript operators for your StrVec, String,
StrBlob, and StrBlobPtr classes.(P.566)
The class StrVec compiled without any error nor warning.Below is the class body:
/**
* #brief The StrVec class a std::vector like class without template
* std:string is the only type it holds.
*/
class StrVec
{
public:
//! default constructor
StrVec():
element(nullptr), first_free(nullptr), cap(nullptr){}
// etc
//! public members
std::string& operator [](std::size_t n) {return element[n];}
const std::string& operator [](std::size_t n) const {return element[n];}
// ^^^^^
// etc
private:
//! data members
std::string* element; // pointer to the first element
std::string* first_free; // pointer to the first free element
std::string* cap; // pointer to one past the end
std::allocator<std::string> alloc;
// etc
};
When compiling the class String, a warning was generated, as shown below:
/**
* #brief std::string like class without template
*
* design:
*
* [0][1][2][3][unconstructed chars][unallocated memory]
* ^ ^ ^
* elements first_free cap
*/
class String
{
public:
//! default constructor
String();
// etc
char operator [](std::size_t n) {return elements[n];}
const char operator [](std::size_t n) const {return elements[n];}
// ^^^^^
private:
//! data members
char* elements;
char* first_free;
char* cap;
std::allocator<char> alloc;
// etc
};
Warning from the compiler:
warning: type qualifiers ignored on function return type [-Wignored-qualifiers]
const char operator [](std::size_t n) const {return elements[n];}
^
The compiler I was using:
gcc version 4.8.1 (Ubuntu 4.8.1-2ubuntu1~13.04)
Why is it so? Is there any significant difference between the two classes?
const char operator [](std::size_t n) const {return elements[n];}
This returns a const copy of elements[n], which is no use at all. You return a const when you don't want the caller changing your stuff, but since you're returning a copy here, you wouldn't be changing anything anyways.
Your first example is returning a const reference, which is what you should do here.
The first version is returning a reference to an array element. Whether or not this is a const reference determines whether you can just read the element's value or write to the element also.
The second version is returning a copy of an array element. If this is deliberate, you only need
char operator [](std::size_t n) const {return elements[n];}
If you wanted two overloads of operator [], one that allows an element to be read and another that allows it to be written, you need to return references instead
char& operator [](std::size_t n) {return elements[n];}
const char& operator [](std::size_t n) const {return elements[n];}
I am fairly new to C++, although I do have some experience programming. I have built a Text class that uses a dynamic char* as it's main member. The class definition is below.
#include <iostream>
#include <cstring>
using namespace std;
class Text
{
public:
Text();
Text(const char*); // Type cast char* to Text obj
Text(const Text&); // Copy constructor
~Text();
// Overloaded operators
Text& operator=(const Text&);
Text operator+(const Text&) const; // Concat
bool operator==(const Text&) const;
char operator[](const size_t&) const; // Retrieve char at
friend ostream& operator<<(ostream&, const Text&);
void get_input(istream&); // User input
private:
int length;
char* str;
};
The issue I am having is I don't know how to use operator[] to assign a char value at the given index that's passed in. The current overloaded operator operator[] is being used to return the char at the index supplied. Anyone have experience with this?
I would like to be able to do something similar to:
int main()
{
Text example = "Batman";
example[2] = 'd';
cout << example << endl;
return 0;
}
Any help and/or advice is appreciated!
Solution provided - Thanks a bunch for all the replies
char& operator[](size_t&); works
You need to provide a reference to the character.
#include <iostream>
struct Foo {
char m_array[64];
char& operator[](size_t index) { return m_array[index]; }
char operator[](size_t index) const { return m_array[index]; }
};
int main() {
Foo foo;
foo[0] = 'H';
foo[1] = 'i';
foo[2] = 0;
std::cout << foo[0] << ", " << foo.m_array << '\n';
return 0;
}
http://ideone.com/srBurV
Note that size_t is unsigned, because negative indexes are never good.
This article is the definitive guide to operator overloading in C++ (which, to be honest, is mainly boilerplate code for syntactic sugar). It explains everything that is possible:
Operator overloading
Here's the portion that is of interest to you:
class X {
value_type& operator[](index_type idx);
const value_type& operator[](index_type idx) const;
// ...
};
And yes, this is possible, for the many of the STL containers (the vector for example), allow for array subscript notation to access data.
So you can do something along the lines of this:
char & operator[]( size_t i )
{
return *(str + i);
}
You should overload operator[] as non const method and return a reference from it
char& operator[](const int&);