赋值运算符是否适用于不同类型的对象? [英] does assignment operator work with different types of objects?

查看:64
本文介绍了赋值运算符是否适用于不同类型的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

class B {
private:
 int c;

}

对不起.发生了错误.赋值运算符有效吗?或者有什么方法可以实现这一目标?[A班和B班没有关系.]

sorry. there happened an error. is assignment operator valid ? or is there any way to achieve this? [There is no relation between A and B class.]

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

} 

非常感谢.

推荐答案

是的,您可以这样做.

#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();
}

这篇关于赋值运算符是否适用于不同类型的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆