开发者

Overload operator= to exchange data between to classes

开发者 https://www.devze.com 2023-04-09 04:36 出处:网络
I\'d like to use two classes A and B for some different types of task. But i want to exchange some data, which should be similar in both, so i\'d like to use a A = B for ex.

I'd like to use two classes A and B for some different types of task. But i want to exchange some data, which should be similar in both, so i'd like to use a A = B for ex.

So, how to use this, with avoiding two-way including in header files?

Example: in class_a.h:

#include class_b.h
class A {
  private:
    int i;
  public:
    A&a开发者_如何学JAVAmp; operator=(B& const b);
}

class_b.h:

#include class_a.h // won't work here ...
class B {
  private:
    unsigned long n;
  public:
    B& operator=(A& const a);
}


You must forward-declare the other class:

class B;
class A {
  private:
    int i;
  public:
    A& operator=(B& const b);
}

Also note that you should probably declare friend class B; inside the definition of A if you don't have getters and need to access B::n.


You need to use a forward declaration:

class A;

class B {
  private:
    unsigned long n;
  public:
    B& operator=(A& const a);
}


Not necessarily better but consider also the idea not to override the assignment, but provide conversions.

You can do like

#include "b.h"
class A
{
public:
    A(const B&);
    operator B() const;
};

If you do a=b; it will become implicitly a=A(b) and if you do b=a; will become implicitly b=a.operator B();

This is like saying that B can be "promoted" to A and A "demoted" to B. But you can do all around A, not modifying B.

0

精彩评论

暂无评论...
验证码 换一张
取 消