本文介绍了重载演员运算符时的歧义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例代码:

#include <iostream>

using namespace std;

class dummy
{
   private:
      int y;

   public:
      dummy(int b = 0) : y(b) {
      }

      friend ostream& operator<<(ostream& os, const dummy& obj);
};

ostream& operator<<(ostream& os, const dummy& obj)
{
   os << obj.y;
   return os;
}

class sample
{
   private:
      int x;

   public:
      sample(int a = 0) : x(a)
      {
      }

      operator dummy()
      {
         dummy d(100);
         return d;
      }

      operator int()
      {
         return x;
      }
};

int main()
{
   sample ob1(5);
   dummy d;

   //d = ob1; //Line1  
   d = (dummy)ob1; //Line2

   cout << d << "\n";
}

在Line1中,完成了隐式转换.我了解在这种情况下隐式强制转换的工作方式.编译器没有给出错误.

In Line1, an implicit cast is done. I understand how the implicit casting works in this case. The compiler gives no errors.

但是在Line2中,对dummy对象执行了对sample对象的显式转换.但是编译器给出了以下错误.

But in Line2, an explicit cast of sample object is done to dummy object. But the compiler gives the following error.

注意:候选对象是:dummy :: dummy(const dummy&)

note: candidates are: dummy::dummy(const dummy&)

注意:dummy :: dummy(int)

note: dummy::dummy(int)

问题:

  1. 为什么会出现这些错误?

  1. Why is these errors occurring?

我不理解错误消息的含义.为什么在错误中提到dummy类的候选函数?

I do not understand the meaning of the error messages. Why the candidate functions of dummy class mentioned in the errors?

推荐答案

该行:

d = (dummy)ob1

尝试执行以下操作:

  1. obj1
  2. 构造dummy对象
  3. 将该临时dummy对象分配给d
  1. Construct a dummy object from obj1
  2. Assign that temporary dummy object to d

第1部分是导致问题的原因.要构造临时dummy对象,编译器必须寻找某种方式将obj1转换为可以构造dummy的类型.它发现有两种方法可以做到这一点:

Part 1 is what causes the problems. To construct the temporary dummy object the compiler must search for some way to convert obj1 into a type which a dummy can be constructed from. It finds that there are two ways to do this:

  1. 致电operator int
  2. 致电operator dummy
  1. Call operator int
  2. Call operator dummy

您没有告诉它要采用这两种选择中的哪一种,因此代码不明确.

You do not tell it which one of these two alternatives you want it to take, and so the code is ambiguous.

您的问题可以按照以下步骤重新创建(除去多余部分):

Your problem could be recreated (with the extraneous parts removed) as follows:

struct t_1 {};
struct t_2 {};
struct sample {
    operator t_1() const{ return t_1(); }
    operator t_2() const{ return t_2(); }
};
void f(t_1) {}
void f(t_2) {}
int main() {
    sample obj1;
    //overload resolution will fail
    //disambiguate with f(obj1.operator t_1()) or f(obj1.operator t_2())
    f(obj1);
}

这篇关于重载演员运算符时的歧义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 19:57