We have the following:
(pseudoish)
class MyClass
{
private:
struct MyStruct{
MyStruct operator=(const MyOtherStruct& rhs);
int am1;
int am2;
};
};
We'd like to overload the = operator in the MyClass.cpp to do something like:
MyStruct&
MyStruct::operator=(const MyOtherStruct& rhs)
{
am1 = rhs.am1;
am2 = rhs.am2;
}
However, it doesn't want to compile. We're getting an error similar to
"missing ; before &"
and
"MyStruct must be a class or namespace if followed by ::"
Is there some concept here I'm missing?
You need to move your operator= for MyStruct into the struct declaration body:
class MyClass
{
private:
struct MyStruct{
int am1;
int am2;
MyStruct& operator=(const MyOtherStruct& rhs)
{
am1 = rhs.am1;
am2 = rhs.am2;
return *this;
}
};
};
Or if that's not possible because MyOtherStruct is incomplete or don't want to clutter the class declaration:
class MyClass
{
private:
struct MyStruct{
int am1;
int am2;
MyStruct& operator=(const MyOtherStruct& rhs);
};
};
inline MyClass::MyStruct& MyClass::MyStruct::operator=(const MyOtherStruct& rhs)
{
am1 = rhs.am1;
am2 = rhs.am2;
return *this;
}
The syntax is
MyStruct& operator=(const MyOtherStruct& rhs) {
// assignment logic goes here
return *this;
}
for an operator directly within the body of MyStruct. Also note that I added the idiomatic return *this to let the assignment return a reference to this object.
EDIT in response to OP editing the question.
You can also declare the operator in the body, and define it somewhere else. In this case, the syntax is:
MyClass::MyStruct& MyClass::MyStruct::operator=(const MyOtherStruct& rhs) {
// assignment logic goes here
return *this;
}
Related
if I have a class with attributes like this:
struct MyClass {
double **arowofpointers;
int capacity;
};
Now, if the task says "make sure this line of code in the main function is legal:
MyClass a(10); //makes a variable whose type is MyClass that has the capacity of 10
But make sure that the following line of code in the main function is not legal:
MyClass a=10;
Still, the following line of your code in the main function should be legal:
a=b+c;
where, a,b and c are all variables whose type is MyClass.
Which constructors should I make? Is there anything I should set on delete or something?
Constructing an instance of type MyClass like this
MyClass a(10);
requires a constructor that takes an integer parameter:
class MyClass {
public:
MyClass(int param);
// ...
};
But as constructors are implicit by default (which is unfortunate), allowing for MyClass a = 10;, you need to make it explicit:
// This constructor must be called explicitly via MyClass(int)
explicit MyClass(int param);
This will make the compiler complain when it encounters MyClass a = 10;.
For the operator part of your question, you might want to have a look at this (the "Arithmetic Operators" part).
MyClass a(10); requires a conversion constructor that takes an integer as input. To prevent MyClass a=10;, make this constructor explicit.
a = b + c; requires an operator+ to concatenate two MyClass objects, and an operator= to assign one MyClass object to another. If you want to support initializations like MyClass a = b;, MyClass a = b + c;, etc, you will also need a copy constructor as well.
And don't forget a destructor.
So, you will need these constructors and operators in your struct:
struct MyClass
{
private:
double **arowofpointers;
int capacity;
public:
// default constructor
MyClass();
// conversion constructor
explicit MyClass(int cap);
// copy constructor
MyClass(const MyClass &src);
// move constructor (C++11 and later only, optional but recommended)
MyClass(MyClass &&src);
// destructor
~MyClass();
// copy assignment operator
MyClass& operator=(const MyClass &rhs);
// move assignment operator(C++11 and later only, optional but recommended)
MyClass& operator=(MyClass &&rhs);
// concatenation operator overload
MyClass operator+(const MyClass &rhs) const;
// compound concatenation assignment operator (optional)
MyClass& operator+=(const MyClass &rhs);
// swap helper
void swap(MyClass &other);
};
// std::swap() overload
void swap(MyClass &lhs, MyClass &rhs);
Where the implementations might look something like this:
#include <algorithm>
MyClass::MyClass()
: arowofpointers(nullptr), capacity(0)
{
}
MyClass::MyClass(int cap)
: arowofpointers(new double*[cap]), capacity(cap)
{
std::fill_n(arowofpointers, capacity, nullptr);
}
MyClass::MyClass(const MyClass &src)
: arowofpointers(new double*[src.capacity]), capacity(src.capacity)
{
std::copy(src.arowofpointers, src.arowofpointers + capacity, arowofpointers);
}
MyClass::MyClass(MyClass &&src)
: arowofpointers(nullptr), capacity(0)
{
src.swap(*this);
}
MyClass::~MyClass()
{
delete[] arowofpointers;
}
MyClass& MyClass::operator=(const MyClass &rhs)
{
if (&rhs != this)
MyClass(rhs).swap(*this);
return *this;
}
MyClass& MyClass::operator=(MyClass &&rhs)
{
MyClass tmp(std::move(*this));
rhs.swap(*this);
return *this;
}
MyClass MyClass::operator+(const MyClass &rhs) const
{
MyClass tmp(capacity + rhs.capacity);
std::copy(arowofpointers, arowofpointers + capacity, tmp.arowofpointers);
std::copy(rhs.arowofpointers, rhs.arowofpointers + rhs.capacity, tmp.arowofpointers + capacity);
return tmp;
}
MyClass& MyClass::operator+=(const MyClass &rhs)
{
MyClass tmp = *this + rhs;
tmp.swap(*this);
return *this;
}
void swap(MyClass &lhs, MyClass &rhs)
{
lhs.swap(rhs);
}
That being said, if you use std::vector instead, then you don't need to handle most of this yourself, let the compiler and STL to the heavy work for you:
#include <vector>
struct MyClass
{
private:
std::vector<double*> arowofpointers;
public:
MyClass();
explicit MyClass(int cap);
MyClass operator+(const MyClass &rhs) const;
MyClass& operator+=(const MyClass &rhs);
void swap(MyClass &other);
};
void swap(MyClass &lhs, MyClass &rhs);
#include <algorithm>
MyClass::MyClass()
: arowofpointers()
{
}
MyClass::MyClass(int cap)
: arowofpointers(cap, nullptr)
{
}
MyClass MyClass::operator+(const MyClass &rhs) const
{
MyClass tmp(arowofpointers.capacity() + rhs.arowofpointers.capacity());
tmp.arowofpointers.insert(tmp.arowofpointers.end(), arowofpointers.begin(), arowofpointers.end();
tmp.arowofpointers.insert(tmp.arowofpointers.end(), rhs.arowofpointers.begin(), rhs.arowofpointers.end();
return tmp;
}
MyClass& MyClass::operator+=(const MyClass &rhs)
{
MyClass tmp = *this + rhs;
tmp.swap(*this);
return *this;
}
void swap(MyClass &lhs, MyClass &rhs)
{
lhs.swap(rhs);
}
I was always overriding operators like this:
class MyClass {
public:
...
MyClass operator+(const MyClass&) const;
private:
int some_number = 5;
}
MyClass MyClass::operator+(const MyClass& rhs) const
{
return MyClass(some_number + rhs.some_number);
}
But today I realized you can create operators with the 'friend' keyword too:
class MyClass {
public:
...
friend MyClass operator+(const MyClass&, const MyClass&);
private:
int some_number = 5;
}
MyClass operator+(const MyClass& lhs, const Myclass& rhs)
{
return MyClass(lhs.some_number + rhs.some_number);
}
Which would be the preferred way considering I want left-sided and right-sided operators and I also (try to) follow the Core Guidelines?
The preferred way is to not even make it a friend:
MyClass operator+(MyClass lhs, Myclass const& rhs)
{
return lhs += rhs;
}
Of course, this does rely on operator+= but that is the more fundamental operation. += alters its left-hand side and should be a member.
I just build a mini program to understand how this will work because i need this for something a bit more difficult but i can't make this work.
I think i need to define operator overload but i dont know how because they are two objects of set<set<a>>
If you compile you will see a big error where it notice that he can't compare myset == myset2 and i think it will say same for operator != and =
#include <set>
using namespace std;
class a{
private:
int a_;
public:
int get_a() const{ return a_; }
void set_a(int aux){ a_=aux;}
bool operator < (const a& t) const{
return this->get_a() < t.get_a();
}
};
class b{
private:
set<set<a> > b_;
public:
void set_(set<a> aux){ b_.insert(aux); }
//Overload operators?
};
int main(){
b myset;
b myset2;
set<a> subset1;
set<a> subset2;
a myint;
myint.set_a(1);
subset1.insert(myint);
myint.set_a(2);
subset1.insert(myint);
myint.set_a(3);
subset1.insert(myint);
myint.set_a(5);
subset2.insert(myint);
myint.set_a(6);
subset2.insert(myint);
myint.set_a(7);
subset2.insert(myint);
myset.set_(subset1);
myset.set_(subset2);
myset2.set_(subset1);
myset2.set_(subset2);
if(myset == myset2){
cout << "They are equal" << endl;
}
if(myset != myset2){
cout << "They are different" << endl;
}
b myset3;
myset3 = myset2; //Copy one into other
}
In order for your code to work you need to specify following operators (note: they are not created by default)
class a{
private:
int a_;
public:
int get_a() const{ return a_; }
void set_a(int aux){ a_=aux;}
/* needed for set insertion */
bool operator < (const a& other) const {
return this->get_a() < other.get_a();
}
/* needed for set comparison */
bool operator == (const a& other) const {
return this->get_a() == other.get_a();
}
};
class b{
private:
set<set<a> > b_;
public:
void set_(set<a> aux){ b_.insert(aux); }
/* needed, because myset == myset2 is called later in the code */
bool operator == (const b& other) const {
return this->b_ == other.b_;
}
/* needed, because myset != myset2 is called later in the code */
bool operator != (const b& other) const {
return !(*this == other);
}
};
You should also take a look at http://en.cppreference.com/w/cpp/container/set and see what other operators std::set uses internally on its elements.
No operator (except for the default operator=(const T&) and operator=(T&&)) is generated by the compiler by default. You should define them explicitly:
class b{
private:
set<set<a> > b_;
public:
void set_(set<a> aux){ b_.insert(aux); }
//Overload operators?
bool operator==(const b& other) const {
return b_ == other.b_;
}
bool operator!=(const b& other) const {
return b_ != other.b_;
}
};
However, this only does not solve the case. Although comparison operators are already defined for std::set<T>, they only work if there are operators for T. So, in this case, you have to define operator== and operator!= for your a class in the same manner as I showed you with b class.
I have a problem in inheriting overloaded + operator.
Let me make an example.
class Data{
protected:
int data[3];
public:
Data(){
data[0] = data[1] = data[2] = 0;
}
Data operator+(const Data& other)
{
Data temp = *this;
for(int i=0;i<3;i++){
temp.data[i] += other.data[i]
}
return temp;
}
};
class DataInterited:public Data{
public:
};
/******************Main*****************/
DataInterited d1,d2,d3;
d3 = d1 + d2; //=> This is compile error
This code generate compile error saying,
no match for ‘operator=’ (operand types are ‘DataInterited’ and ‘Data’)
I think I have to implement operator+ for DataInherited so that it return DataInherited instance. But in this way, I cannot avoid code duplication.
Is there any way to make d3=d1+d2; line correct while avoiding duplicating the + operator implementation?
There are a couple of things you need to know.
First, always implement operator+ as a free function in terms of operator+=. It saves code duplication and is optimally efficient.
Second, you had no constructor in DataInherited that could take a Data as its argument. This is important because the result of Data::operator+ is a Data, not a DataInherited.
corrected code:
#include <iostream>
#include <algorithm>
class Data{
protected:
int data[3];
public:
Data(){
data[0] = data[1] = data[2] = 0;
}
Data(const Data& other)
{
std::copy(std::begin(other.data), std::end(other.data), data);
}
Data& operator=(const Data& other)
{
std::copy(std::begin(other.data), std::end(other.data), data);
return *this;
}
Data& operator+=(const Data& other)
{
for(int i=0;i<3;i++){
data[i] += other.data[i];
}
return *this;
}
};
Data operator+(Data left, const Data& right)
{
return left += right;
}
class DataInterited:public Data{
public:
DataInterited(Data d = {})
: Data(std::move(d))
{}
};
using namespace std;
auto main() -> int
{
DataInterited d1,d2,d3;
d3 = d1 + d2; //=> This is no longer a compile error
return 0;
}
Koenig operator forwarding to an increment_by function.
Derived classes can implement their own increment_by overloads if they want different behavior.
SFINAE stuff skipped, so bad types will give hard errors.
class Data{
public:
template<class D, class Rhs>
friend D operator+=(D&& lhs, Rhs&& rhs){
increment_by(lhs,std::forward<Rhs>(rhs));
return std::forward<D>(lhs);
}
template<class Lhs, class Rhs>
friend Lhs operator+(Lhs lhs, Rhs&& rhs){
lhs+=std::forward<Rhs>(rhs);
return std::move(lhs);
}
friend void increment_by(Data& self, Data const&other){
for(int i=0;i<6;i++){
self.data[i] += other.data[i];
}
}
};
Both + and += are template friends and hence the types passed can be derived classes. So type isn't lost,
increment_by needs overiding if derived type needs new behaviour. If not, leave it alone.
live example.
Do not leave the type needlessly. Converting from base to derived basically throws out the point of the derived type.
Is it possible to overload a private inner class member as a non-member? It seems to me the only way is to overload as a member.
class Foo
{
private:
struct Bar
{
int a;
char b;
Bar& operator+=(const Bar& rhs)
{
a += rhs.a;
return *this;
}
// Only possibility?
inline Bar operator+(const Bar& rhs)
{
Bar bar;
bar.a = this->a + rhs.a;
bar.b = this->b;
return bar;
}
};
// Cannot do this as takes implicit reference (to Foo?).
inline Bar operator+(Bar lhs, const Bar& rhs)
{
lhs += rhs;
return lhs;
}
};
// Cannot do this as Bar private.
inline Foo::Bar operator+(Foo::Bar lhs, const Foo::Bar& rhs)
{
lhs += rhs;
return lhs;
}
I guess I could just use the member overload, but I understand it's preferable to overload the + operator as a non-member, and I would like to separate the implementation.
Doesn't look like anyone wants to claim this, I'll provide the answer for completeness. Credit goes to juanchopanza and Igor Tandetnik.
The solution is to use friend.
class Foo
{
private:
struct Bar
{
int a;
char b;
Bar& operator+=(const Bar& rhs)
{
a += rhs.a;
return *this;
}
};
friend Bar operator+(Bar, const Bar&);
};
Foo::Bar operator+(Foo::Bar lhs, const Foo::Bar& rhs)
{
lhs += rhs;
return lhs;
}