未调用类型转换运算符

时间:2015-08-05 18:05:02

标签: c++ c++11 typecast-operator typecasting-operator

我正在尝试为对象之间的类型转换执行一些示例代码,只需按照显示的here进行操作。

这是父类

// ParentClass.h
class ParentClass {
public:
    ParentClass();
    virtual ~ParentClass();
};

这只是一些概念证明,它唯一能做的就是打印一些东西

#include <iostream>
#include "ParentClass.h"
ParentClass::ParentClass()
{
    std::cout << "Parent\tDefault constructor\n";
}
ParentClass::~ParentClass()
{
    std::cout << "Parent\tDestructor\n";
}

然后,派生类

// ChildClass.h
#include "ParentClass.h"

class ChildClass: public ParentClass {
public:
    ChildClass();
    // conversion constructor
    ChildClass( const ParentClass& p );
    // conversion from assignment
    ChildClass& operator= ( const ParentClass & p );
    // type-cast operator
    operator ParentClass();
    // destructor
    virtual ~ChildClass();
};

然后,代码,也是相当愚蠢的

// ChildClass.cpp

#include <iostream>
#include "ChildClass.h"

ChildClass::ChildClass()
{
    std::cout << "Child\tDefault constructor\n";
}
ChildClass::~ChildClass()
{
    std::cout << "Child\tDestructor\n";
}
// conversion constructor
ChildClass::ChildClass( const ParentClass& p )
{
    std::cout << "Child\tConversion constructor\n";
}
// assignment operator    
ChildClass& ChildClass::operator= ( const ParentClass & p )
{
    std::cout << "Child\toperator= conversion\n";
    return *this;
}    
// type-cast operator
ChildClass::operator ParentClass()
{
    std::cout << "Child\toperatorParentClass()\n";
    return ParentClass();
}

然后,我在主要功能

中做了一些转换
    std::cout << "calls Parent default constructor\n";
    ParentClass foo;
    std::cout << "calls Parent to child constructor\n";
    ChildClass bar = foo;
    std::cout << "calls assignment operator from child\n";
    bar = foo;
    std::cout << "calls Child type-cast operator\n";
    foo = bar;
    std::cout << "Exit\n";

但是当我运行它时,代码没有从派生类进入类型转换操作符,它只是打印出来:

calls Parent default constructor
Parent  Default constructor
calls Parent to child constructor
Parent  Default constructor
Child   Conversion constructor
calls assignment operator from child
Child   operator= conversion
calls Child type-cast operator
Exit
Child   Destructor
Parent  Destructor
Parent  Destructor

我对此感到茫然,因为我在上面的链接中尝试了代码,它就像它应该的那样工作。

1 个答案:

答案 0 :(得分:5)

派生到基础转换从不调用转换函数。 [class.conv.fct] / P1:

  

转换函数永远不会用于转换(可能是   cv-qualified)对象(可能是cv-qualified)相同的对象类型   (或对它的引用),对(可能是cv认证的)基类   那种类型(或对它的引用),或(可能是cv-qualified)   void

foo = bar;中,bar直接绑定到const ParentClass&的隐式声明的复制赋值运算符的ParentClass参数。