简体   繁体   English

多个 inheritance 模板的成员函数歧义

[英]Member functions ambiguity with multiple inheritance templates

I am public deriving two instances of class template 'Area', one int and another char into an separate class 'Rectangle'.我公开将 class 模板“区域”的两个实例,一个 int 和另一个 char 派生到一个单独的 class“矩形”中。

template<class T>
class Area {
  public:
    T a;
    T getArea() { return a; }
    void setArea(T t) { a = t; }
};  

class Rectangle : public Area<int>, public Area<char> {
};  

int main() {
  Rectangle a;
  a.setArea(1);
  std::cout << a.getArea() << std::endl;
  Rectangle b;
  b.setArea('c');
  std::cout << b.getArea() << std::endl;
}   

And I see ambiguity with setArea and getArea.我看到 setArea 和 getArea 有歧义。 Why is that so?为什么呢? I thought after public Area, public Area there would be two definitions of setArea.我想在 public Area 之后, public Area 会有两个 setArea 的定义。 First, void setArea(int) and another void setArea(char).首先,void setArea(int) 和另一个 void setArea(char)。 Please correct me if I am wrong.如果我错了,请纠正我。 And If I am correct, why the ambiguity?如果我是正确的,为什么会模棱两可?

If you bring the name setArea from both the base classes into the derived class with using statements:如果using语句将两个基类中的名称setArea带入派生的 class:

class Rectangle : public Area<int>, public Area<char> {
  using Area<int>::setArea;
  using Area<char>::setArea;
};  

the compiler will be able to call the right setArea .编译器将能够调用正确的setArea

This will not work for getArea as the 2 functions differ only in their return type.这对getArea不起作用,因为这两个函数仅在返回类型上有所不同。 You will have to distinguish between them at the call site:您必须在呼叫站点区分它们:

std::cout << a.Area<int>::getArea() << std::endl;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM