最烦躁的解析 [英] Most vexing parse

查看:143
本文介绍了最烦躁的解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从这里获得了代码。

  class Timer {
public:
Timer();
};

class TimeKeeper {
public:
TimeKeeper(const Timer& t);

int get_time()
{
return 1;
}
};

int main(){
TimeKeeper time_keeper(Timer());
return time_keeper.get_time();
}

从它的外观,它应该得到编译错误,

  TimeKeeper time_keeper(Timer 

但是它只会发生在 return time_keeper.get_time(); time_keeper(Timer())发现歧义 code>



<这是由于 TimeKeeper time_keeper(Timer())的原因,这是因为 ); 被解释为一个函数声明,而不是一个变量定义。这本身不是一个错误,但是当您尝试访问time_keeper(这是一个函数,而不是TimeKeeper实例)的 get_time()成员时,失败。



这是编译器如何查看代码:

  int main(){
// time_keeper被解释为一个带有函数参数的函数声明。
//这绝对是*不是*我们期望的,但是从编译器POV它没关系。
TimeKeeper time_keeper(Timer(* unnamed_fn_arg)());

//编译器抱怨:time_keeper是函数,你怎么期望我调用
//它的成员?它没有成员函数!
return time_keeper.get_time();
}


I got the code from here.

class Timer {
 public:
  Timer();
};

class TimeKeeper {
 public:
  TimeKeeper(const Timer& t);

  int get_time()
  {
      return 1;
  }
};

int main() {
  TimeKeeper time_keeper(Timer());
  return time_keeper.get_time();
}

From the looks of it, it should get compile error due to the line:

TimeKeeper time_keeper(Timer());

But it only happens if return time_keeper.get_time(); is present.

Why would this line even matter, the compiler would spot ambiguity on time_keeper(Timer() ) construction.

解决方案

This is due to the fact that TimeKeeper time_keeper(Timer()); is interpreted as a function declaration and not as a variable definition. This, by itself, is not an error, but when you try to access the get_time() member of time_keeper (which is a function, not a TimeKeeper instance), your compiler fails.

This is how your compiler view the code:

int main() {
  // time_keeper gets interpreted as a function declaration with a function argument.
  // This is definitely *not* what we expect, but from the compiler POV it's okay.
  TimeKeeper time_keeper(Timer (*unnamed_fn_arg)());

  // Compiler complains: time_keeper is function, how on earth do you expect me to call
  // one of its members? It doesn't have member functions!
  return time_keeper.get_time();
}

这篇关于最烦躁的解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆