我对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;
}
答案 0 :(得分:0)
C ++不允许您使用协变参数类型覆盖虚函数。您的派生运算符根本不会覆盖抽象赋值运算符,它定义了一个完全正交的运算符,只是因为它具有相同的运算符名称。
你必须小心创建这样的函数,因为如果两个实际的派生类型不一致,那么几乎可以肯定,赋值将是荒谬的。我会重新考虑是否可以通过替代方法更好地满足您的设计需求。
答案 1 :(得分:0)
这有点旧,但万一其他人偶然发现它:
要添加Mark的答案,您可以通过实施
来实现Derived & operator=(const Abstract & rs);
在这种情况下,您可能需要通过投射使用rs
:dynamic_cast<const Derived &>(rs)
当然这应该只是小心翼翼。
完整的实施将是:
Derived & Derived::operator=(const Abstract & hs)
{
if (this == &hs)
return *this;
Abstract::operator=(hs);
style = new char[std::strlen(dynamic_cast<const Derived &>(hs).style) + 1];
std::strcpy(style, dynamic_cast<const Derived &>(hs).style);
return *this;
}