繁体   English   中英

将基类对象分配给派生类对象

[英]Assignment of base class object to derived class object

为什么会error: no match for 'operator=' in 'y = x'以下代码error: no match for 'operator=' in 'y = x'中的error: no match for 'operator=' in 'y = x'
不能仅仅将b的a分量分配为a-object = a-object吗?

struct a {int i;};
struct b : public a {int j;};

int main()
{
    a x;
    b y;

    x.i = 9;
    y.j = 5;

    y = x; // error: no match for ‘operator=’ in ‘y = x’

    // expected: y.i = 9

    return 0;
}

您没有明确定义任何赋值运算符,因此编译器将为每个结构生成其自己的默认运算符。 b编译器的默认赋值运算符将b作为输入,并将分配两个成员。 使用继承时,赋值运算符不会自动继承。 这就是为什么你不能传递一个ab -存在没有赋值操作符b接受一个a的输入。 如果要允许这样做,则需要告诉编译器尽可能多的信息,例如:

struct a
{
    int i;

    a& operator=(const a &rhs)
    {
        i = rhs.i;
        return *this;
    }
};

struct b : public a
{
    int j;

    using a::operator=;

    b& operator=(const b &rhs)
    {
        *this = static_cast<const a&>(rhs);
        j = rhs.j;
        return *this;
    }
};

int main()
{
    a x;
    b y;
    b z;
    ...
    y = x; // OK now
    y = z; // OK as well
    ...    
    return 0;
}

不可以,因为即使类相关,它们也是不同的类型。

考虑一下,即使它被允许并且可以按照您的预期工作,分配后yj的值是多少?

由于错误状态,您需要实现一个赋值运算符 也就是说,该函数告诉您的程序如何将一个对象分配给另一个对象。 如果您在网上搜索,则可以找到很多信息,例如,在http://www.cplusplus.com/articles/y8hv0pDG/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM