C++中的对象初始化
Object initialization in C++
我正在查看某人的代码,我不明白对象是如何在这里初始化的:
template <typename String>
void test_numbers()
{
SampleClass<String> compare;
String lhs = "abc";
String rhs = "efg";
check_equality(compare(lhs, rhs), true);
}
对象比较创建为类类型SampleClass,然后在作为参数传递时分配2个字符串。这个初始化是如何工作的?有什么意见吗?建议?
//I am initialised with my default constructor (no args)
SampleClass<String> compare;
//I am initialised with my `const char*` constructor (and assignment operator)
String lhs = "abc";
String rhs = "efg";
//Compare (already initialised) is being invoked by it's `operator()`
check_equality(compare(lhs, rhs), true);
compare已构建。它实现了一个operator()
,允许它作为一个函数出现,接受参数。
你可以很容易地自己做。
struct op_test{
int i;
op_test(int i_) : i(i_){}
int operator()(int j)const { return j*i; }
};
:::
op_test ot(5);
ot(6); //5*6
这之所以有用,是因为我们可以做这样的事情。
std::vector<int> a(700); //700 ints
std::transform(a.begin(), a.end(), b.begin(), op_test(5));
//or
std::transform(a.begin(), a.end(), b.begin(), &my_func); //calls a function
std::transform(a.begin(), a.end(), b.begin(), [](int i){ return i*5; }); //lambda
请参见此处:http://msdn.microsoft.com/en-us/library/5tk49fh2(v=vs.80).aspx与有用http://en.cppreference.com/w/cpp/algorithm
它只是创建一个类型为SampleClass<String>
的自动变量。然后用两个String
参数调用它的operator()
。
相关文章:
- C++使用整数的压缩数组初始化对象
- 如何使用cudaMallocManaged在指针位置初始化对象?(C++)
- 在 c++ 中初始化对象
- C++ 手动分配和初始化对象
- 使用运算符"="在C++中用值初始化对象
- 当我不需要数据库中的所有值时,如何部分初始化 c++ 对象?
- 如何初始化对象数组?
- 在C++中使用默认构造函数初始化对象的不同方法
- 使用默认构造函数初始化对象的不同方法
- 是否可以在编译时初始化对象的 C 样式函数指针,以便它调用对象的成员函数?
- 如何在线程中初始化对象,然后在其他地方使用它?
- 在没有默认构造函数时使用垃圾数据初始化对象
- 如果在 C++ 构造函数中以错误的顺序初始化对象数据,会发生什么类型的错误
- 初始化对象以在 C++08 中作为参数传递的首选语法是什么?
- 在 c++ 中复制对未初始化对象的引用
- 在成员变量在另一个文件中发生更改后,调用与初始化对象分开的函数
- 在不放置新运算符的情况下,在预分配的内存上使用虚函数初始化对象 - 这可能吗?如果没有,为什么
- 复制 CTOR 与赋值运算符以初始化对象(性能)
- 当您通过分配初始化C 对象时会发生什么
- 获取未初始化对象成员的地址是否定义良好?