c++ - 未调用派生类的虚拟赋值运算符

标签 c++ assignment-operator

我是 C++ 的新手,正在努力掌握虚拟赋值。下面的程序由一个具有两个数据成员的抽象基类和一个具有一个数据成员的派生类组成。当我将抽象指针设置为派生对象时,程序使用 operator= 的抽象版本而不是派生版本,即使它们都被声明为“虚拟”。我在这里做错了什么?

提前致谢

周杰伦

#include <iostream>
#include <cstring>

class Abstract
{
  protected:
        char * label;
        int rating;
    public:
        Abstract(const char * l = "null", int r = 0);
        virtual Abstract & operator=(const Abstract & rs);
        virtual ~Abstract() { delete [] label; }
        virtual void view() const = 0;

};

class Derived : public Abstract
{
    private:
        char * style;
    public:
        Derived(const char * s = "none", const char * l = "null",
                  int r = 0);
        ~Derived() { delete [] style; }
        virtual Derived & operator=(const Derived & rs);
        virtual void view() const;

};

Abstract::Abstract(const char * l , int r )
{
    label = new char[std::strlen(l) + 1];
    std::strcpy(label, l);
    rating = r;
}

Abstract & Abstract::operator=(const Abstract & rs)
{
    if (this == &rs)
            return *this;
    delete [] label;
    label = new char[std::strlen(rs.label) + 1];
    std::strcpy(label, rs.label);
    rating = rs.rating;
    return *this;
}

Derived::Derived(const char * s, const char * l, int r)
         : Abstract(l, r)
{
    style = new char[std::strlen(s) + 1];
    std::strcpy(style, s);
}

Derived & Derived::operator=(const Derived & hs)
{
    if (this == &hs)
        return *this;
    Abstract::operator=(hs);
    style = new char[std::strlen(hs.style) + 1];
    std::strcpy(style, hs.style);
    return *this;
}

void Derived::view() const
{
    std::cout << "label: " << label << "\nrating: "
              << rating << "\nstyle: " << style;
}

int main ()
{
    using namespace std;
    char label[20], style[20];
    int rating;


    cout << "label? ";
    cin >> label;
    cout << "rating? ";
    cin >> rating;
    cout <<"style? ";
    cin >> style;

    Derived a;
    Abstract * ptr = &a;
    Derived b(style, label, rating);
    *ptr = b;
    ptr->view();

    return 0;
}

最佳答案

C++ 不允许您使用协变参数类型覆盖虚函数。您的派生运算符根本不会覆盖抽象赋值运算符,它定义了一个完全正交的运算符,仅因为它是相同的运算符名称。

创建此类函数时必须小心,因为如果两个实际的派生类型不一致,几乎可以肯定赋值是无意义的。我会重新考虑是否可以通过替代方法更好地满足您的设计需求。

关于c++ - 未调用派生类的虚拟赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7946997/

相关文章:

c++ - 覆盖不明确的继承

c++ - 前向声明未按预期工作

c++ - 隐式生成的赋值运算符应该是 & ref 限定的吗?

c++ - RAII 和赋值

c++ - 在宏中锁定 ostream 输出

c++ - 为什么在未复制指针时会出现错误?

c++ - 具有相同字段类型的结构和类的不同 sizeof()

c++ - 语义略有不同的复制构造函数和赋值运算符中是否存在陷阱?

c++ - is_assignable 和 std::unique_ptr

Java - 循环声明外的逗号运算符