class Port
{
riêng tư:
char * brand;
char style[20]; // i.e., tawny, ruby, vintage
int bottles;
công cộng:
Port(const char * br = "none", const char * st = "none", int b = 0);
Port(const Port & p); // copy constructor
virtual ~Port() {delete[] brand; }
Port & operator=(const Port & p);
Port & operator+=(int b); // adds b to bottles
Port & operator-=(int b); // subtracts b from bottles, if
int BottleCount() const { return bottles; }
virtual void Show() const;
friend ostream & operator<<(ostream & os, const Port & p);
};
class VintagePort : public Port // style necessarily = "vintage"
{
riêng tư:
char * nickname; // i.e., "The Noble" or "Old Velvet", etc.
int year; // vintage year
công cộng:
VintagePort();
VintagePort(const char * br, const char *st, int b, const char * nn, int y);
VintagePort(const VintagePort & vp);
~VintagePort() { delete[]nickname;}
VintagePort & operator=(const VintagePort & vp);
virtual void Show() const;
friend ostream & operator<<(ostream & os, const VintagePort & vp);
};
我必须解释为什么operator=()
Và operator<<()
不是虚拟的。我认为operator<<()
不能是虚拟的,因为只有类方法可以,但我不知道 operator=()。基础类的指针如何知道operator=()
中的哪一个?它必须使用?
第二个问题是关于我如何制作operator<<()
表现得像一个虚拟方法,例如:
basicClass B;
inheritClass I;
basicClass *ptr;
ptr=&I;
std::cout << ptr // Here I'd like to use operator<<(std::ostream, inheritClass)
operator =
不是虚拟的,因为它没有标记为 ảo
. operator =
的声明看起来像这样
//No virtual here
Port& operator =(const Port&);
但是,如果 operator =
是虚拟的,它会像这样声明
virtual Port& operator =(const Port&);
^^^^^^^ Virtual here!
自 operator =
不是虚拟的编译器在编译时使用静态链接。这意味着调用的函数取决于它所引用的变量的类型。考虑这段代码:
VintagePort vp;
//Calls VintagePort::operator =(const VintagePort&)
vp = VintagePort();
Port* p = &vp;
//Calls Port::operator =(const Port&)
*p = Port();
VintagePort::operator =
当它作为 VintagePort
访问时被调用, 然而, Port::operator =
当它作为 Port
访问时被调用. (实例đây. )
制作operator <<
表现得好像它是虚拟的你必须在你的类中声明一个虚拟成员函数来进行打印。像这样
//Inside Port
virtual void Print(std::ostream& os) const
{
os << brand << ' ' << style << ' ' << bottles;
}
然后在派生自 Port
的每个类中(如 VintagePort
)您将覆盖该方法以打印该派生类的值。所以对于 VintagePort
你可以这样做
//Inside VintagePort
void Print(std::ostream& os) const
{
//Make Port print first
Port::Print(os);
os << ' ' << nickname << ' ' << year;
}
sau đó vàooperator <<
您所要做的就是调用 Print
论据上的方法。看起来像这样:
std::ostream& operator <<(std::ostream& os, const Port& p)
{
P.Print();
return os;
}
另外,您不必重载 operator <<
对于每个派生类,因为重载只需要 Port
中的虚函数类。
Tôi là một lập trình viên xuất sắc, rất giỏi!