I have class Human, and a class List.How to overload operator +=, so i can do:
list+=human
in that way i add one object of Human class to my list.
Thank you.
If you really want to do this you can define the operator on namespace level:
list& operator+=(list& lhs, human const& rhs)
{
lhs.add(rhs); // actually add human to the list
return lhs;
}
Either declare the operator as a member function of the class List like
class List
{
public:
List & operator +=( const Human &human )
{
// something like
// push_back( human );
return *this;
}
//…
};
Or define it as a non class function like
List & operator +=( List &list, const Human &human )
{
// something like
// push_back( human );
return list;
}
If the implementation of the operator requires to access non-public data members of the class List then the function should be a friend function of the class as for example
class List
{
public:
friend List & operator +=( List &, const Human & );
//…
};
you can see this question as a reference, you can define both of your classes and then define the "add" overloading operator of List Class later.
Related
I would like to leave the two instances unchanged, and return a new one.
Currently I am doing it this way:
class myClass {
public:
myClass operator +(const myClass &obj) {
myClass ret = *this;
// some operation
return ret;
}
// functions...
};
It works, but I am not sure, if it is the correct way
Edit
The operator + is just an example. I'm just curious, how the immutable functions/methods should be written in C++
If myClass is supposed to be immutable under addition, you probably want to make operator+ a free function rather than a class member. (You might have to make it a friend function.)
myClass operator+(const myClass &lhs, const myClass &rhs) {
return myClass( /* some operation */ );
}
Note that both operands are taken by const reference, so you know you cannot accidentally change them (maintaining the immutability property). You're returning a new instance of myClass, which is now immutable. You construct and return the result in one step, because, if myClass really is immutable, you might not be able to default construct one and then set its value.
Here's a stupid example:
class myClass {
public:
explicit myClass(int x) : m_x(x) {}
friend myClass operator+(const myClass &lhs, const myClass &rhs);
private:
int m_x;
};
myClass operator+(const myClass &lhs, const myClass &rhs) {
return myClass(lhs.m_x + rhs.m_x);
}
If you really want to implement it as a class method, the method should be marked const to ensure the implementation doesn't accidentally mutate the left-hand instance.
Binary arithmetic operators (like operator+) are often defined in terms of the arithmetic self-assignment operators (like operator+=), which are obviously not immutable. If we add this method to myClass:
myClass &operator+=(const myClass &rhs) {
m_x += rhs.m_x;
return *this;
}
Then the common idiom for defining operator+ would be:
myClass operator+(const myClass &lhs, const myClass &rhs) {
myClass result = lhs;
result += rhs;
return result;
}
Now the implementation of operator+ doesn't require any of the private members of the class, so it no longer needs to be declared as a friend function.
Is it even possible?
So I have
class Organism{
// ....
public:
virtual std::string type(){
return "Organism"
}
// ....
}
I also have derived clases ant, beetle, witch return "Ant" / "Beetle"
I have one more class World where things happen.
In World class there are Organism* world[20][20];
I want to create operator that comperas word[x][y] to world[x1][y1]
I managed to create operator:
friend bool operator== (const Organism &lhs, const Organism &rhs){
return lhs.type() == rhs.type();
}
but what I want is something like this:
friend bool operator== (const Organism* lhs, const Organism* rhs){
return lhs->type() == rhs->type();
}
but it doesnt allow it VS13 says "Error: nonmember operator requires a parameter with class or enum type".
How to achieve this?
ps. I can't even write const after closing ).
How to write copy constructor for a template class. So that if the template parameter is another user defined class it's copy constructor is also get called.
Following is my class
template <typename _TyV>
class Vertex {
public:
Vertex(_TyV in) : m_Label(in){ }
~Vertex() { }
bool operator < ( const Vertex & right) const {
return m_Label < right.m_Label;
}
bool operator == ( const Vertex & right ) const {
return m_Label == right.m_Label;
}
friend std::ostream& operator << (std::ostream& os, const Vertex& vertex) {
return os << vertex.m_Label;
}
_TyV getLabel() { return m_Label;}
private:
_TyV m_Label;
public:
VertexColor m_Color;
protected:
};
Either a) not at all, just rely on the compiler-provided default; or b) by just invoking the copy constructor of the member:
template <typename T> struct Foo
{
T var;
Foo(const Foo & rhs) : var(rhs.var) { }
};
The point is of course that the compiler-provided default copy constructor does precisely the same thing: it invokes the copy constructor of each member one by one. So for a class that's composed of clever member objects, the default copy constructor should be the best possible.
Assuming _TyV is a value type:
Vertex( Vertex const& src )
: m_Label( src.m_Label )
{}
Aren't those names within class instances reserved by the implementation, by the way?
The C++ standard reserves a set of names for use by C++ implementation and standard libraries [C++ standard 17.6.3.3 - Reserved names]. Those include but are not limited to:
Names containing a double underscore.
Names that begin with an underscore followed by an uppercase letter.
Names that begin with an underscore at the global namespace.
template <typename T>
class Vertex {
public:
//this is copy-constructor
Vertex(const Vertex<T> &other)
: m_Color(other.m_Color),m_Label(other.m_Label)
{
//..
}
//..
};
But I don't think you need to explicitly define the copy-constructor, unless the class have pointer member data and you want to make deep-copy of the objects. If you don't have pointer member data, then the default copy-constructor generated by the compiler would be enough.
suppose i have 2 objects of a class and it has one int data member.
i want to add those integer data to other object and store the output in the first obj's data member.I can overload the + operator and use the statement like below
X+Y //where X and Y are objects of one class.
if i have to add like below
X+10// here i want to add 10 to the data member of X.
for above also i can overload the operator +.
but if i have 10+X and i want to add 10 to the data member of X how could i do it?
The same way:
MyClass operator+(MyClass const& lhs, MyClass const& rhs);
MyClass operator+(MyClass const& lhs, int rhs);
MyClass operator+(int lhs, MyClass const& rhs);
(operator+ should not normally be a member.)
If you overload operator+, you'll also want to overload +=. One
frequent idiom involved implementing + in terms of +=. This can
be more or less automated (if you have a lot of classes
supporting operators) by defining something like:
template<typename DerivedType>
class ArithmeticOperators
{
public:
friend DerivedType operator+(
DerivedType const& lhs,
DerivedType const& rhs)
{
DerivedType result(lhs);
result += rhs;
return result;
}
// And so on for the other operators...
protected:
~ArithmeticOperators() {}
};
template<typename DerivedType, typename OtherType>
class MixedArithmeticOperators
{
public:
friend DerivedType operator+(
DerivedType const& lhs,
OtherType const& rhs)
{
DerivedType result(lhs);
result += rhs;
return result;
}
friend DerivedType operator+(
OtherType const& lhs,
DerivedType const& rhs)
{
DerivedType result(rhs);
result += lsh;
return result;
}
// And so on: non-commutative operators only have the
// first.
protected:
~MixedArithmeticOperators() {}
};
, then deriving from whatever is needed: in your case:
class MyClass : public ArithmeticOperators<MyClass>,
MixedArithmeticOperators<MyClass, int>
You have to create an overloaded operator as a free function with the correct parameter order:
// This will match "int + YourClass" additions
YourClass operator+(int Left, const YourClass & Right)
{
// If your addition operation is commutative, you can just call the other
// version swapping the arguments, otherwise put here your addition logic
return Right + Left;
}
If the operator needs to fiddle with the internals of your class you can make it friend.
As others pointed out, there are some best/common practices that you should follow if you implement operator+, I suggest you to have a look to the great C++-FAQ on operator overloading for more info about them.
Don't overload the operator + as a member function of the class.
You can either define a global function operator + with two parameters or make operator + a friend of your class (In that case you should be having a parameterized constructor to convert 10 to an object of your class-type).
Define a non-member stand-alone free function as:
sample operator+(int leftOperand, const sample & rightOperand)
{
//...
}
Although you can do that using a global operator+, I would advise not to do it.
Only use operator overloading for data types for which the operators are immediately clear, e.g.:
complex numbers
strings (+,- ok, but * probably doesn't make much sense here)
The risk with overloaded operators is that the compiler may perform unwanted conversions, especially if you didn't make the single-argument constructor explicit.
You should define a non-member friend function
YourClass operator+(const YourClass &a, const YourClass&b) {
// do the math here
}
it should be friend to get to the private members of YourClass. Also you should create constructor for YourClass that takes int.
In this way you've got one operator+ and for every other then int you just create another constructor.
I'm trying to overload the assignment operator and would like to clear a few things up if that's ok.
I have a non member function, bool operator==( const MyClass& obj1, const myClass& obj2 ) defined oustide of my class.
I can't get at any of my private members for obvious reasons.
So what I think I need to do is to overload the assignment operator. And make assignments in the non member function.
With that said, I think I need to do the following:
use my functions and copy information using strcpy or strdup. I used strcpy.
go to the assignment operator, bool MyClass::operator=( const MyClass& obj1 );
Now we go to the function overloading (==) and assign obj2 to obj1.
I don't have a copy constructor, so I'm stuck with these:
class Class
{
private:
m_1;
m_2;
public:
..
};
void Class::Func1(char buff[]) const
{
strcpy( buff, m_1 );
return;
}
void Class::Func2(char buff[]) const
{
strcpy( buff, m_2 );
return;
}
bool Class& Class::operator=(const Class& obj)
{
if ( this != &obj ) // check for self assignment.
{
strcpy( m_1, obj.m_1 );
// do this for all other private members.
}
return *this;
}
bool operator== (const Class& obj1, const Class& obj2)
{
Class MyClass1, MyClass2;
MyClass1 = obj1;
MyClass2 = obj2;
MyClass2 = MyClass1;
// did this change anything?
// Microsofts debugger can not get this far.
return true;
}
So as you can probably tell, I'm completely lost in this overloading. Any tips? I do have a completed version overloading the same operator, only with ::, so my private members won't lose scope. I return my assignments as true and it works in main. Which is the example that I have in my book.
Will overloading the assignment operator and then preforming conversions in the operator== non member function work? Will I then be able to assign objects to each other in main after having completed that step?
You have a couple of obvious mistakes here and there is some confusion about what you are actually trying to achieve. Firstly, the assignment operator operator = is meant to copy the value from one instance to another. The return value of the assignment operator is almost always a non constant reference to the target of the copy, so that you can chain assignments:
Class & operator=(const Class &rhs)
{
// copy the members
return *this;
}
The comparison operator operator == is meant to perform a comparison of two instances. It returns a boolean true if they are equal:
boolean operator==(const Class &rhs) const
{
// check if they are equal
return something;
}
The confusion is why are you trying to copy values around, or maybe assign to the instances in the comparison operator?
Op== isn't the assignment operator. T& Op= (const T&) is.
bool operator==(const T& lhs, const T& rhs) is the operation to compare two Ts. It returns true if lhs is equal to rhs, for whatever definition of "equal" you want to code.
I am guessing that you want to compare the two objects. In that case, you can just overload the operator == in class "Class". You don't need assignment operator.
class Class
{
public:
Class(int i) : m_i(i){}
bool operator==( const Class& rhs)
{
return m_i == rhs.m_i;
}
private:
int m_i;
};
int main()
{
Class t1(10), t2(10);
bool b = (t1 == t2);
}
I am not sure whether I understood the question correctly. But if you trying to check the equality using a non-member function and can't do this only because you can't access the private members of the class, then you can declare the non-member function as a friend function and use it like this:
class Test
{
public:
Test(int i) : m_i(i){}
private:
int m_i;
friend bool operator==(Test& first, Test& second);
};
bool operator==(Test& first, Test& second)
{
return first.m_i == second.m_i;
}
int main()
{
Test t1(10), t2(10);
bool b = (t1 == t2);
}