我基本上有以下两个类,我使用return-by-value函数来创建对象。 在下面的Bar类中,我有两个Foo类成员对象。我怎样才能正确初始化每一个 两个对象分开? 下面,我将对显示的编译器错误进行说明。
template < typename T >
class Foo{
public:
Foo( );
Foo( const Foo<T> & );
~Foo();
friend Foo<T> createFoo1( double, bool );
friend Foo<T> createFoo2( double, bool );
friend Foo<T> createFoo3( int );
private:
std::vector<T> m_data;
};
template < typename T >
Foo<T> createFoo1( double param1, bool param2 ){
Foo<T> myFoo;
// fill myFoo.
return (myFoo);
}
template < typename T >
class Bar{
public:
Bar( );
Bar( const Foo<T> &, const Foo<T> & );
Bar( const Bar<T> & );
~Bar( );
friend Bar<T> createBar1( double, bool );
private:
Foo<T> m_fooY;
Foo<T> m_fooX;
};
template < typename T >
Bar<T> createBar1( double param1, bool param2 ){
Bar<T> myBar( createFoo1<T>(param1, param2), createFoo1<T>(param1, param2) ); //OK
return (myBar);
//Bar<T> myBar;
//myBar.m_fooY(createFoo1<T>(param1, param2)); // <- error C2064: term does not evaluate to a function taking 1 arguments
//myBar.m_fooX(createFoo1<T>(param1, param2)); // <- error C2064: term does not evaluate to a function taking 1 arguments
//return (myBar);
}
答案 0 :(得分:0)
除了通过构造函数之外,您还可以设置字段m_fooX和m_fooY:
template < typename T >
Bar<T> createBar1( double param1, bool param2 ){
Bar<T> myBar;
myBar.m_fooY = createFoo1<T>(param1, param2);
myBar.m_fooX = createFoo1<T>(param1, param2);
return myBar;
}