最麻烦的解析
我从此处获取了代码。
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() )
构造上的歧义。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为
TimeKeeper time_keeper(Timer());
被解释为函数声明而不是变量定义。这本身并不是一个错误,但是当您尝试访问 time_keeper(这是一个函数,而不是 TimeKeeper 实例)的get_time()
成员时,您的编译器会失败。这是编译器查看代码的方式:
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 theget_time()
member of time_keeper (which is a function, not a TimeKeeper instance), your compiler fails.This is how your compiler view the code: