我是 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/