[英]Wrapper around a class C++
suppose a C++ class has a constructor (among other constructors) of the form 假设C ++类具有以下形式的构造函数(除其他构造函数外)
Foo::Foo( FILE *fp ) { etc... }
Now I want create a wrapper class of the form 现在我要创建表单的包装器类
class WFoo {
Foo::Foo A;
Foo::Foo B;
};
with constructor 与构造函数
WFoo::WFoo(FILE *fa, FILE *fb) {
A(fa), B(fb);
}
What is wrong with the definition of WFoo? WFoo的定义有什么问题? Thanks in advance.
提前致谢。
This doesn't make any sense... 这没有任何意义...
class WFoo {
Foo::Foo A;
Foo::Foo B;
};
You mean... 你的意思是...
class WFoo {
public:
Foo A;
Foo B;
WFoo(FILE* fa, FILE* fb);
};
WFoo::WFoo(FILE* fa, FILE* fb) :
A(fa), B(fb)
{
}
Remember also that fields are initialized not in the order you read in the constructor but in the order they are declared in the class! 还请记住,字段的初始化不是按照您在构造函数中读取的顺序进行,而是按照在类中声明的顺序进行初始化!
So... 所以...
#include <iostream>
struct XFoo
{
XFoo(const char* s) { std::cout << s << std::endl; }
};
struct YBar
{
XFoo a;
XFoo b;
YBar() : a("A"), b("B") {}
};
struct ZBar
{
XFoo b;
XFoo a;
ZBar() : a("A"), b("B") {}
};
int main()
{
YBar y;
ZBar z;
return 0;
}
will print out... 将打印出来...
A
B
B
A
That's an initializer list but the syntax is off. 这是一个初始化列表,但语法已关闭。 Try:
尝试:
WFoo::WFoo(FILE* fa, FILE* fb) : A(fa), B(fb)
{
}
The syntax you're looking for is: 您要查找的语法是:
WFoo::WFoo(FILE *fa, FILE *fb) : A(fa), B(fb) { ... }
And, unless Foo
is in a namespace called Foo
and WFoo
is not: 并且,除非
Foo
位于名为Foo
的命名空间中,否则WFoo
不会:
class WFoo {
Foo A;
Foo B;
};
If the code you've posted is psudocode, then there is nothing wrong with the definition of WFoo
. 如果你发布的代码是psudocode,那么就没有什么不妥的定义
WFoo
。
If, on the other hand, the code you've posted is not intended to be psudocode, but actual code you'd try to compile & run, then here is what's wrong with WFoo
: 另一方面,如果您发布的代码不是psudocode,而是您尝试编译和运行的实际代码,则这是
WFoo
:
Foo A;
Foo A;
Not Foo::Foo A
unless Foo
is in a namespace called Foo
(which would be bad) Foo::Foo A
除非Foo
在名为Foo
的命名空间中(这很糟糕) This is what you want: 这就是你想要的:
WFoo::WFoo(FILE* fa, FILE* fb)
: A(fa), B(fb)
{
}
Note that the initializer list comes before the body of the constructor. 请注意,初始值设定项列表位于构造函数的主体之前。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.