【问题标题】:Why is the compiler calling the default constructor?为什么编译器调用默认构造函数?
【发布时间】:2011-11-25 15:11:33
【问题描述】:

为什么我会收到以下错误消息? (为什么编译器会尝试调用默认构造函数?)

#include <cmath>

template<typename F> struct Foo { Foo(F) { } };

int main()
{
    Foo<double(double)>(sin);   // no appropriate default constructor available
}

【问题讨论】:

    标签: c++ constructor default-constructor


    【解决方案1】:

    因为没有区别

     Foo<double(double)>(sin);   
    

     Foo<double(double)> sin;   
    

    两者都声明了一个名为 sin 的变量。

    括号是多余的。您可以放置​​任意数量的括号。

    int x;             //declares a variable of name x
    int (x);           //declares a variable of name x
    int ((x));         //declares a variable of name x
    int (((x)));       //declares a variable of name x
    int (((((x)))));   //declares a variable of name x
    

    都是一样的!

    如果你想创建类的临时实例,将sin作为参数传递给构造函数,那么这样做:

    #include<iostream>
    #include <cmath>
    
    template<typename F> 
    struct Foo { Foo(F) { std::cout << "called" << std::endl; } };
    
    int main()
    {
        (void)Foo<double(double)>(sin); //expression, not declaration
        (Foo<double(double)>(sin));     //expression, not declaration
        (Foo<double(double)>)(sin);     //expression, not declaration
    }
    

    输出:

    called
    called
    called
    

    演示:http://ideone.com/IjFUe

    它们有效,因为所有三种语法都强制它们成为表达式,而不是 variable 声明。

    但是,如果你尝试这个(正如@fefe 在评论中建议的那样):

     Foo<double(double)>(&sin);  //declaration, expression
    

    它不起作用,因为它声明了一个引用变量,并且由于它没有初始化,你会得到编译错误。见:http://ideone.com/HNt2Z

    【讨论】:

    • O_________O ... [每日 wtf]
    • 哇...那我该如何调用构造函数呢?
    • @Mehrdad:将行转换为void 可能会起作用,因为它会强制整行成为一个表达式,因此会创建一个临时的。
    • @bitmask:没关系,我实际上想出了另一种方法——Foo&lt;double(double)&gt;::Foo(sin) 似乎也有效。耶。
    • 我觉得明确取sin的地址也可以解决问题,比如Foo&lt;double(double)&gt;(&amp;sin)
    【解决方案2】:

    我想您正在尝试从函数指针类型制作模板。不知道 double(double) 是什么意思,但如果你真的想引用函数指针类型,那你应该这样做:

    Foo<double(*)(double)> SinFoo(sin);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-06
      • 2019-05-17
      • 1970-01-01
      • 2015-09-05
      • 2013-03-20
      • 1970-01-01
      • 2018-10-04
      相关资源
      最近更新 更多