C ++覆盖来自相同基本模板类的函数,具有多个继承模糊函数调用

时间:2017-12-12 10:17:48

标签: c++ c++11 multiple-inheritance ambiguous name-lookup

我需要调用从基类派生的init(int* iNumber)函数。

BaseClass.h

#pragma once
#include "stdafx.h"
template <class T>
class BaseClass
{
public:
    BaseClass() {}
    virtual ~BaseClass() {}
    virtual void init(T* object) = 0;
};

ChildClass.h

#pragma once
#include "BaseClass.h"

class ChildClass : public BaseClass<int>, public BaseClass<float>
{
public:
    ChildClass() {}
    virtual ~ChildClass() {}
};

ChildClassImpl.h

#pragma once
#include "ChildClass.h"
class ChildClassImpl : public ChildClass
{
public:
    ChildClassImpl();
    virtual ~ChildClassImpl();
private:
    void init(int* iNumber) override;
    void init(float* fNumber) override;
};

ChildClassImpl.cpp

#include "stdafx.h"
#include <iostream>
#include "ChildClassImpl.h"

ChildClassImpl::ChildClassImpl(){}

ChildClassImpl::~ChildClassImpl(){}

void ChildClassImpl::init(int* iNumber)
{
    std::cout << "Integer constructor: " << *iNumber << std::endl;
}

void ChildClassImpl::init(float* fNumber)
{
    std::cout << "Float constructor: " << *fNumber << std::endl;
}

MainClass

#include "stdafx.h"
#include <iostream>
#include "ChildClassImpl.h"

using namespace std;

int main()
{
    ChildClass* childClass = new ChildClassImpl();
    int x = 10;
    childClass->init(&x);
    cout << "Test" << endl;
    getchar();
    return 0;
}

在编译时,这会给出错误

Severity  Code    Description Project File    Line Error
(active)      "BaseClass<T>::init [with T=int]" is
ambiguous ConsoleApplication4 d:\Learning\ConsoleApplication4\ConsoleApplication4\ConsoleApplication4.cpp 14

我在这里做错了什么?我怎么能用最小的改变来解决它?

1 个答案:

答案 0 :(得分:0)

此代码失败,因为C ++在重载解析和访问控制检查之前执行名称查找。这是确定init属于哪个类范围的第一步。在这种情况下,结果将不明确,因为init可以引用BaseClass<int>::initBaseClass<float>::init。引入额外的using声明会将这两个函数带入ChildClass范围:

class ChildClass : public BaseClass<int>, public BaseClass<float>
{
public: using BaseClass<int>::init;
public: using BaseClass<float>::init;

因此,名称查找将确定init引用ChildClass::init,编译器将继续重载解析。

或者你可以进行演员表演(这绝对不方便):

static_cast<BaseClass<int> *>(childClass)->init(&x);