c++ - 虚方法,operator=(), operator<<();

标签 c++ class inheritance objective-c++

class Port
{
private:
    char * brand;
    char style[20]; // i.e., tawny, ruby, vintage
    int bottles;
public:
    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"
{
private:
    char * nickname; // i.e., "The Noble" or "Old Velvet", etc.
    int year; // vintage year
public:
    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=()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 =不是虚拟的,因为它没有标记为 virtual . 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 访问时被调用. (实例here。)


制作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;
}

然后在operator <<您所要做的就是调用 Print论据上的方法。看起来像这样:

std::ostream& operator <<(std::ostream& os, const Port& p)
{
    P.Print();
    return os;
}

另外,您不必重载 operator <<对于每个派生类,因为重载只需要 Port 中的虚函数类。

关于c++ - 虚方法,operator=(), operator<<();,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30697903/

相关文章:

c++ - 如何从普通bst继承红黑树

c# - 静态接口(interface)等效 C#

C++程序找不到boost

c++ - 您应该如何阅读以下文档?

c++ - 增量时间始终为零

java - 调用一个方法但它不起作用

PHP面向对象问题

c++ - 在c中的函数内部定义一个函数

c++ - 为什么在作为值返回时在类内部定义结构需要范围解析?

java - 继承中的协方差