我正在尝试在另一个构造函数中初始化一个类构造函数。 GCC引发了错误,'Type'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);
}
}
答案 0 :(得分:5)
两个问题:
首先,你的foo构造函数应该是公开的,如Mark的回答所述。
其次,要使用构造函数初始化成员,您应该使用以下语法:
foo2(type _arg1, type _arg2) :
member(_arg1, _arg2)
{ /* code */ }
答案 1 :(得分:0)
你的建造者不公开;默认情况下,除非另行指定,否则类中的所有内容都是私有的。我不确定这会解释您确切的错误消息。
答案 2 :(得分:0)
您需要初始化列表:
foo2(type _arg1, type _arg2) : member(_arg1,_arg2) { }
答案 3 :(得分:0)
您正在尝试使用member
的构造函数。您应该在初始化列表中而不是在构造函数体中执行此操作,即:
foo2(type _arg1, type _arg2)
: member(_arg1, _arg2)
{
}
答案 4 :(得分: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
这表明你不应该在这里发布“sorta like”代码并期待有用的答案。