根据按值返回函数正确初始化对象
Correct initialization of objects based on return-by-value functions
我基本上有以下两个类,我使用按值返回函数来创建对象。在下面的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);
}
下面是设置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;
}
相关文章:
- C++使用整数的压缩数组初始化对象
- 如何使用cudaMallocManaged在指针位置初始化对象?(C++)
- 在 c++ 中初始化对象
- C++ 手动分配和初始化对象
- 使用运算符"="在C++中用值初始化对象
- 当我不需要数据库中的所有值时,如何部分初始化 c++ 对象?
- 如何初始化对象数组?
- 在C++中使用默认构造函数初始化对象的不同方法
- 使用默认构造函数初始化对象的不同方法
- 是否可以在编译时初始化对象的 C 样式函数指针,以便它调用对象的成员函数?
- 如何在线程中初始化对象,然后在其他地方使用它?
- 在没有默认构造函数时使用垃圾数据初始化对象
- 如果在 C++ 构造函数中以错误的顺序初始化对象数据,会发生什么类型的错误
- 初始化对象以在 C++08 中作为参数传递的首选语法是什么?
- 在 c++ 中复制对未初始化对象的引用
- 在成员变量在另一个文件中发生更改后,调用与初始化对象分开的函数
- 在不放置新运算符的情况下,在预分配的内存上使用虚函数初始化对象 - 这可能吗?如果没有,为什么
- 复制 CTOR 与赋值运算符以初始化对象(性能)
- 当您通过分配初始化C 对象时会发生什么
- 获取未初始化对象成员的地址是否定义良好?