0

我正在尝试在另一个构造函数中初始化一个类构造函数。GCC 引发错误,'类型'foo'没有呼叫运算符。'这个伪代码应该解释我的意图。

class foo {  
    type arg1, arg2;
    foo (type _arg1, type _arg2) {  
        _arg1=arg1;  
        _arg2=arg2;  
    }  
}

class foo2 {  
    foo member;

    foo2(type _arg1, type _arg2) {  
        member(_arg1, _arg2);  
    }  
}
4

5 回答 5

5

两个问题:

首先,您的 foo 构造函数应该是公共的,如马克的回答中所述。

其次,要使用其构造函数初始化成员,您应该使用以下语法:

foo2(type _arg1, type _arg2) :
   member(_arg1, _arg2)
   { /* code */ }  
于 2011-04-27T02:04:56.653 回答
0

你想要初始化列表:

foo2(type _arg1, type _arg2) : member(_arg1,_arg2) { }
于 2011-04-27T02:02:55.863 回答
0

您正在尝试使用member' 构造函数。您应该在初始化列表中而不是在构造函数主体中执行此操作,即:

foo2(type _arg1, type _arg2)
    : member(_arg1, _arg2)
{  
}  
于 2011-04-27T02:03:00.420 回答
0

伪代码可以解释你的意图,但它不能解释你的错误,因为它不会以你描述的方式出错:

class foo {  
    type arg1, arg2;
    foo (type _arg1, type _arg2) {  
        _arg1=arg1;  
        _arg2=arg2;  
    }  
}

class foo2 {  
    foo member;

    foo2(type _arg1, type _arg2) {  
        member(_arg1, _arg2);  
    }  
}

尽管它确实产生了有用的诊断:

gcc -Wall junk.cc 
junk.cc: In constructor ‘foo2::foo2(int, int)’:
junk.cc:12:32: error: no matching function for call to ‘foo::foo()’
junk.cc:3:5: note: candidates are: foo::foo(int, int)
junk.cc:1:11: note:                 foo::foo(const foo&)
junk.cc:13:28: error: no match for call to ‘(foo) (int&, int&)’
junk.cc: At global scope:
junk.cc:14:5: error: expected unqualified-id at end of input

这表明您不应该在这里发布“类似”的代码并期待有用的答案。

于 2011-04-27T02:08:24.837 回答
0

您的构造函数不是公开的;默认情况下,除非您另外指定,否则类中的所有内容都是私有的。我不确定这是否解释了您的确切错误消息。

于 2011-04-27T02:00:42.863 回答