Let's say I have a String class that I want to be able to construct or assign with a pointer, but disallow compiling with an explicit std::nullptr assignment:
class String {
public:
String(const char *);
friend bool operator== (const String &, const char *);
friend bool operator!= (const String &, const char *);
// some important things left out
private:
String(std::nullptr_t);
}
The purpose is to give "error: 'operator=' is a private member of 'String'" if I try to write "str = NULL", which helps me identify some bugs in an old codebase. Obviously, the public constructor should handle the nullptr case as well. Additionally, it helps me identify some similar issues such as "str = 0", which the compiler will report as ambiguous.
My question is - can I do something similar with binary comparison operators, operator== and operator!=? I would like the compiler to report an attempted comparison to std::nullptr_t, which is also very common in my codebase.
Whenever you want to prohibit calling a certain function you can append = delete, which was introduced in C++11:
friend bool operator==(const String&, std::nullptr_t) = delete;
friend bool operator!=(const String&, std::nullptr_t) = delete;
Whenever you try to compare your type with nullptr you get this compiler error:
function "operator==(const String &, std::nullptr_t)" cannot be referenced -- it is a deleted function
Related
I've made a class Block and a struct coords and while implementing the operators i came up with the errors:
'coords operator[](const Block&, const size_t&)' must be a nonstatic member function
'bool operator=(Block&, const Block&)' must be a nonstatic member function
I've declared these 2 in the header file of the class Block as follows:
class Block
{
friend Block operator+(const Block&, const coords&);
friend Block operator+(const Block&, const Block&);
friend coords operator[](const Block&, const std::size_t&);
friend void operator+=(Block&, const coords&);
friend void operator+=(Block&, const Block&);
friend bool operator=(Block&, const Block&);
//...
};
Only the operators [] and = get this error, and I'm not sure why.
I've tried to change the return value and parameter types but it keeps getting the same problem.
Are these two operators special? Or is there an error on my declarations?
I've searched for ways to solve this problem, but couldn't find a suitable answer.
Thank you for the replies.
Not all operators can be overloaded using non-member functions. [] and = are two such operators. They can be overloaded only as member functions.
See http://en.cppreference.com/w/cpp/language/operators for more details.
Those operators cannot be declared as friends. Instead you should declare like this:
coords operator[](const std::size_t&);
bool operator=(const Block&);
Your operators are also not really following conventions. Operators += and = should be returning a Block& namely *this.
The reason is exactly what the error message says: those two have to be non-static member functions. Get rid of the friend from in front of them and remove the first argument.
Further, operator+= is usually implemented as a member function, too, although it doesn't have to be. But if it is, it gives you an easy way to implement operator+ without making it a friend.
#R Sahu's link was useful, showing that [] and = can no be declared as non-member, but it didn't really explain why.
#Baum mit aguen's link cleared some other questions too.
(Thanks for the information)
So, I adjusted my code to this new information as follows:
Block.h
class Block
{
public:
//...
coords* operator[](size_t);
Block operator=(Block);
//...
};
Block.cpp
//...
coords* Block::operator[](size_t index)
{
if(index >= 0 && index < block.size())
return &block.at(index);
coords *tmp = new coords(-1, -1);
return tmp;
}
Block Block::operator=(Block b2)
{
block.empty();
block.reserve(b2.block.size());
append(b2.block);
return *this;
}
//...
This way you can call *(*b1)[0] = c1; being Block* b1 and coords c1.
The friend modifier is useful for other types of implementations, although I only realized after that the implementation of inline had to be done in the header file, not on the cpp.
Block.h
class Block
{
public:
//...
friend std::ostream& operator<<(std::ostream&, const Block&);
friend std::ostream& operator<<(std::ostream&, Block&);
//...
};
inline std::ostream& operator<<(std::ostream& out, const Block& b)
{
// do something
return out;
};
inline std::ostream& operator<<(std::ostream& out, Block& b)
{
// do something
return out;
};
In this case, you need to pass the "this" parameter has to be passed to the function also as these are non-member functions and should be implemented outside the class, in the header file.
I hope this helps, good coding everyone.
I am trying to overload the == operator in C++.
#include <string>
using namespace std;
namespace date_independent
{
class clock
{
public:
int clockPair[2] = {0,0};
operator string() const
{
string hourString;
string minString;
if(clockPair[0]<10)
{
hourString = "0"+to_string(clockPair[0]);
}
else
{
hourString = to_string(clockPair[0]);
}
if(clockPair[1]<10)
{
minString = "0"+to_string(clockPair[1]);
}
else
{
minString = to_string(clockPair[1]);
}
return hourString+":"+minString;
};
bool operator ==(const clock&clockOne, const clock&clockTwo) const
{
return string(clockOne)==string(clockTwo);
};
};
};
There is much more code than I have included, but this is the important part. I want it so that the == operator can compare two objects of class clock. E.g., object1==object2. Is there anybody that can help me?
A binary operator like == can be overloaded either as a member function with a single parameter (this being the left-hand operand, and the parameter being the right-hand one), or as a non-member function with two parameters for the two operands.
So either
move your operator declaration outside the class declaration (moving the definition to a source file, or declaring it inline if you keep the definition in the header); or
add friend to the definition, so that it declares a non-member in the surrounding namespace; or
remove the first argument from the member function, using this instead.
As a member, it would look like
bool operator==(const const & clockTwo) const {
return string(*this) == string(clockTwo);
}
You might also want to compare the two integer values directly to save the expense of making strings. You should also remove the rogue ; after the function and namespace definitions, although most modern compilers shouldn't object to their presence.
Your comparison function has been written to take two clock objects and compare them, so it should be a non-member function (after the class definition), without the const qualifier.
bool operator==(const clock& clockOne, const clock& clockTwo)
{
return string(clockOne) == string(clockTwo);
}
When you have an operator inside the class definition, the left-hand argument is implicitly provided for you (it's *this), so if you wanted to implement it there you'd need something like:
bool operator==(const clock& clockTwo) const
{
return string(*this) == string(clockTwo);
}
Still, that's not recommended for == as if you have say an implicit constructor from another type T, you won't be able to write code ala my_t == my_clock with the member version unless T provides a suitable comparison operator (for clock or string). A non-member operator gives more symmetric operation.
Overloading can be done inside or outside the class definition. If you want to do it inside, the function receives only one argument. You should compare this with that argument.
bool operator ==(const clock&clockTwo) const
{
return string(*this)==string(clockTwo);
}
Note the const after the argument, it means that you won't change this inside the function.
On the other hand, if you want to do it outside the class definition, it needs two arguments, and you should compare them.
bool operator ==(const clock&clockOne, const clock&clockTwo)
{
return string(clockOne)==string(clockTwo);
}
Also note that it'll be faster to compare the clockPair of the objects rather than making the string and comparing them.
Though your question is poorly worded I believe that you are asking why the operator you've defined is not working?
If you are defining the operator as a member of the class it only takes one parameter. For example:
class clock {
bool operator ==(const clock& rhsClock) const
{
// Note: this is the lhsClock
return string(*this) == string(otherClock);
}
};
When you define the operator as a free function (not as a part of the class) then you need to define both parameters:
class clock {
// ... class declaration ...
};
bool operator ==(const clock& lhsClock, const clock& rhsClock)
{
return string(lhsClock) == string(rhsClock)
}
Where the comparison would look like this:
if (lhsClock == rhsClock) // ... do something ...
I have
class Conatact{
.....
bool operator<(Contact &c);
};
bool operator<(Contact &c)
{
return this.getName<c.getName();
}
it says `bool operator<(Contact&)' must take exactly two arguments
when I try to change it to have two arguments
bool operator<(Contact &c)
{
return this.getName<c.getName();
}
it says it must take exactly one argument
I think you need to indicate to the compiler it's a member implementation by supplying a fully qualified name:
bool Conatact::operator<(Contact &c)
{
return this->getName() < c.getName();
}
It would be a good idea to make your operator const, and to make the Contact &c const as well.
Without the scope resolution qualifier, the compiler thinks that you are defining a "free-standing" operator to compare contacts, in which case the operator would indeed need to take two arguments:
bool operator<(const Contact &lhs, const Contact &rhs) {
...
}
Can you explain for me what the typedef here is doing and what the purpose is?
class C
{
public:
...
typedef bool (C::*implementation_defined_bool_type)(bool) const;
operator implementation_defined_bool_type() const {
return _spi ? &C::isPersistent : 0;
}
};
Can you explain for me what the typedef is doing here?
typedef bool (C::*implementation_defined_bool_type)(bool) const;
typedefs a pointer to a const member function of a type C, which takes a bool as input parameter and also returns a bool.
While,
operator implementation_defined_bool_type() constÂ
Takes in an object of type C and returns a type implementation_defined_bool_type.
It is known as an Conversion Operator.
what is the purpose of it?
It implements the "Safe Bool Idiom", which aims to validate an object in a boolean context.
Note that the Safe Bool Idiom is obsolete with the C++11 Standard.
Good Read:
The Safe Bool Idiom
I'm making some stack, in which I need to uses this kind of comparison in some function. But I got stuck since I don't know how the prototype for this should look like.
I have the following line in a function.
template <class T>
void function1(T i)
{
if(i == 'a')
//do something
}
I wonder know how the overload prototype should look like for it?
EDIT
Dunno if it's worth to mention, anyway this is what I have tried so far
template
bool Stack<T>::operator==(char c) const
{
cout << c << endl; // just some test
}
No need to comment how this function works, as I have not finished it yet. This part will compile, however at the part where I call this function for the first time is in the Stack::push(T i). The compiler will complain that there are no matching function for this.
error: no match for 'operator==' in 'i == '#''
For overloading operators, the name of the function is operator followed by the actual operator, so operator==. It returns bool. I don't know what your arguments should be based on your code. Probably Stack<T>&, and you need two of them to compare if it's a free function, and one to compare to this if it's a member function.
If you have ways to convert to a Stack<T>, then prefer a free function so that you can convert the left-hand-side.
I'm not sure I understand your question. In order for an instantiation of template function function1 to be well-formed, you'll have to provide a operator== which compares a T and (I'll suppose) a char.
Now, you have two options here :
Provide a bool operator==(char) const member function in your type, for example :
struct A {
bool operator==(char) const { /* ... */ }
};
function1(A()); // OK : comparison uses A::operator==(char)
Provide bool operator==(const T &, char) as a free function, for example :
struct A { /* ... */ };
bool operator==(const A &, char) { /* ... */ }
function1(A()); // OK : comparison uses operator==(const A &, char)
So every T in your function1(t) has to implement operator ==;
For example, as a member function
class A
{
public:
bool operator == (char) const;
};
or a non-member operator:
class A
{
public:
friend bool operator == (const A&, char);
};