赋值运算符是否适用于不同类型的对象?

5 c++ virtual-functions operator-overloading

class A {
public:
void operator=(const B &in);
private:
 int a;
};

class B {
private:
 int c;

}
Run Code Online (Sandbox Code Playgroud)

抱歉.发生了一个错误.赋值运算符有效吗?或者有没有办法实现这一目标?[A和B级之间没有关系.]

void A::operator=(const B& in) 
{ 
a = in.c;

} 
Run Code Online (Sandbox Code Playgroud)

非常感谢.

Shr*_*ree 9

是的,你可以这样做.

#include <iostream>
using namespace std;

class B {
  public:
    B() : y(1) {}
    int getY() const { return y; }
  private:
     int y;
};


class A {
  public:
    A() : x(0) {}
    void operator=(const B &in) {
       x = in.getY();
    }
    void display() { cout << x << endl; }
  private:
     int x;
};


int main() {
   A a;
   B b;
   a = b;
   a.display();
}
Run Code Online (Sandbox Code Playgroud)