简体   繁体   English

在C ++中实例化一个类:奇怪的语法错误

[英]Instantiating a Class in C++: Strange Syntax Bug

I've never run into this before in C++ but it's odd that it still compiles but doesn't do what I expected. 我以前从未在C ++中遇到过这个问题,但奇怪的是它仍然可以编译,但却没有达到我的预期。 Can someone tell me what it does do? 有人能告诉我它做了什么吗? Please see the code, more info follows. 请参阅代码,更多信息如下。

#include <iostream>
using namespace std;

class Test{
    public:
        Test();
};

Test::Test(){ cout << "ctor" << endl; }

int main(void){

    Test t();  // this compiles but doesn't call the constructor

    return(0);
}

It will compile, but if I try to use "t" it won't. 它会编译,但如果我尝试使用“t”则不会。 I was only dependent on constructor functionality, and my code didn't work as expected. 我只依赖于构造函数,我的代码没有按预期工作。 The solution is to lose the parenthesis "Test t();" 解决方案是丢失括号“Test t();” to "Test t;". “测试t;”。 My question is what is going on in the "Test t();" 我的问题是“测试t();” example, and what does the compiler think is happening that it lets it compile. 例如,编译器认为它正在发生什么,它允许它编译。

This is the Most Vexing Parse . 这是令人烦恼的解析 Basically, according to the C++ parsing rules, what you have there isn't an object of type Test named t , but rather a function declaration for a function t which takes zero arguments and returns a Test . 基本上,根据C ++解析规则,你所拥有的不是Test名为t的类型的对象,而是函数t的函数声明,它接受零参数并返回Test

Incidentally, clang++ actually recognizes this situation and emits a warning, telling you that this probably isn't doing what you want. 顺便说一句,clang ++实际上会识别这种情况并发出警告,告诉你这可能不是你想要的。

This is a common problem that is aptly named as the most vexing parse . 这是一个常见的问题,恰如其分地被称为最令人烦恼的解析 Your line Test t(); 你的行Test t(); can be interpreted in one of two ways. 可以用两种方式之一来解释。

  1. It can declare a variable t which is of type Test 它可以声明一个类型为Test的变量t
  2. It can declare a function t() , which returns a Test value and takes no arguments 它可以声明一个函数t() ,它返回一个Test值并且不带参数

The C++ standard unfortunately requires the compiler to consider the second alternative, which is quite a vexing parse. 不幸的是,C ++标准要求编译器考虑第二种选择,这是一个非常令人烦恼的解析。

The easiest way to fix that parse is to get rid of the parenthesis and simply declare your variable as such : 解决该解析的最简单方法是删除括号并简单地声明您的变量:

Test t; // Will call the default constructor

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

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