gpt4 book ai didi

c++ - 来自基类和派生类的多态赋值运算符

转载 作者:行者123 更新时间:2023-11-30 04:55:53 24 4
gpt4 key购买 nike

我希望能够将派生对象或基对象复制到派生对象,并且我希望根据复制对象的类型以多态方式选择正确的运算符。

此代码无效,我希望 b1 = (A&)b2; 使用 B & operator= (B const &other) 因为 b2B,但它使用 B & operator= (A const &other):

#include<iostream> 

using namespace std;

class A {
public:
A & operator= (A const &other) {
// Here copy A members...
cout<<"A to A"<<endl;
return *this;
}
};

class B: public A {
public:
B & operator= (A const &other) {
A::operator=(other); // Copy A members.
cout<<"A to B"<<endl;
return *this;
}
B & operator= (B const &other) {
A::operator=(other); // Copy A members.
// Here copy B members...
cout<<"B to B"<<endl;
return *this;
}
};

int main()
{
B b1, b2;
A a2;
b1 = b2;
cout<<endl;
b1 = (A&)b2;
cout<<endl;
b1 = a2;
cout<<endl;
return 0;
}

我想我必须做一些虚拟的,但我不知道怎么做。

最佳答案

我希望能够将派生对象或基础对象复制到派生对象,这是设计不佳的表现。

最好争取一种设计,其中类层次结构中只有叶级类是可实例化的。这允许您拥有干净的、非虚拟的、赋值运算符函数只处理正确类型的对象。

class A {
public:

// Make A uninstantiable.
virtual ~A() = 0;

A & operator= (A const &other) {
// Here copy A members...
cout<<"A to A"<<endl;
return *this;
}
};

class B: public A {
public:

// Not necessary.
// B & operator= (A const &other) { ... }

B & operator= (B const &other) {
A::operator=(other); // Copy A members.
// Here copy B members...
cout<<"B to B"<<endl;
return *this;
}
};

关于c++ - 来自基类和派生类的多态赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52858602/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com