【问题标题】:C object with () - what does it do? [duplicate]带有 () 的 C 对象 - 它有什么作用? [复制]
【发布时间】:2013-10-11 10:47:56
【问题描述】:

这段特定的代码有什么作用?更准确地说,test tob(); 是做什么的?做什么?

class test {
 private:
  int a;
  int b;
 public:
  test (int);
  test();
};
test::test() {
 cout<<"default";
}
test::test (int x=0) {
 cout<<"default x=0";
}
int main() {
 test tob();
}

我不知道测试 tob();做,但它没有给出任何编译错误。

【问题讨论】:

    标签: c++


    【解决方案1】:
    test tob();
    

    声明一个返回类型为test的函数。 它不创建对象。也称为most vexing parse

    创建test 对象:

    test tob;
    

    另外,使用默认参数定义函数(包括构造函数)的方式不正确。

    test::test (int x=0) {  // incorrect. You should put it in function when it's first declared
     cout<<"default x=0";
    }
    

    下面的代码应该可以工作:

    class test {
      int a;
      int b;
    
     public:
      explicit test (int = 0);    // default value goes here
    };
    
    test::test (int x) {          
     cout<<"default x=0";
    }
    
    int main() {
     test tob;    // define tob object
    }
    

    【讨论】:

    • 感谢您的澄清。
    • @anikondemand 不用担心。很高兴它有帮助!
    • 这不是所谓的令人烦恼的解析。这只是令人烦恼。 :)
    • @hvd 绝对是,但这条错误信息似乎非常顽固。我想单词最终意味着人们使用它们的目的,所以及时这将是最令人烦恼的解析,尽管它不像原来那样令人烦恼。
    • 这是最令人头疼的解析,en.wikipedia.org/wiki/Most_vexing_parse
    猜你喜欢
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-24
    • 2014-01-03
    相关资源
    最近更新 更多