C ++模板参数化构造函数 [英] C++ Templates parameterized constructor
问题描述
你好,
我是C ++模板的新手,并且在将c#代码移植到c ++时遇到问题
我想创建一个可以容纳任何类型的循环缓冲区,因此需要模板.
在C#中,我有这个(简化代码)
Hello,
I''m new to templates in C++ and I''m having issues to port my c# code to c++
I want to create a circular buffer which can hold any type thus a template is required.
In c# I have this (simplified code)
public class buffer<T>;
{
private T[] items;
public buffer(int size)
{
items = new T[size];
}
}
也很容易使用:
also it''s easy to use:
buffer<int> buf = new buffer<int>(10);
这将根据类型为int的缓冲区创建一个长度为10的缓冲区...
无论如何,所以现在我在将其移植到不受管理的c ++时遇到问题.
我已经阅读了一些有关c ++模板的教程,以获得某种理解,但是到目前为止,我还无法解决这个问题.这可能很简单,但是语法不同(我猜是这样).
所以到目前为止我的C ++代码:
标头:
That creates a buffer from the type int that will be 10 long...
Anyway, so now I''m having problems porting this to unmanaged c++.
I''ve read a couple of tutorials on templates in c++ to get some sort of understanding, but I''m not able to work this out so far. It''s probably very easy, but just a different syntax (I guess).
So my C++ code so far:
header:
template <class T>
class buffer {
public:
buffer(unsigned int size);
private:
T* items;
}
源文件:
source file:
template <class T>
buffer<t>::buffer(unsigned int size)
{
items = new T[size];
}</t>
可以正确编译,但是我现在知道如何创建新缓冲区...
this compiles correctly, but I have now idea how to create a new buffer...
buffer<int> buf;
不能正常工作,我想出的其他东西也不能正常工作.
谁能告诉我如何以一种整洁的方式解决此问题:)
is not working, neither is the rest of what I came up with.
Can anybody tell me how to fix this in a neat way :)
Thanks in advance!
推荐答案
首先,不要为模板代码使用单独的源文件-将其放在头文件中:
First, don''t use a separate source file for your template code - put it in the header file:
template <class T>
class buffer {
public:
buffer(unsigned int size)
{
items = new T[size];
}
private:
T* items;
};
没有定义默认的构造函数,因此在实例化类时需要提供大小:
There is no default constructor defined, so you need to supply the size when instantiating the class:
buffer<int> buf(10);
...并且不要忘记在delete [] items
的生命周期末尾添加析构函数.
...and don''t forget to add a destructor to delete [] items
at the end of its lifetime.
//C++_Class_Templates.cpp
#include <iostream.h>
#include <vector>
template <typename t>
class MyQueue
{
std::vector<t> data;
public:
void Add(T const &);
void Remove();
void Print();
};
template <typename t> void MyQueue<t> ::Add(T const &d)
{
data.push_back(d);
}
template <typename t> void MyQueue<t>::Remove()
{
data.erase(data.begin( ) + 0,data.begin( ) + 1);
}
template <typename t> void MyQueue<t>::Print()
{
std::vector<int>::iterator It1;
It1 = data.begin();
for ( It1 = data.begin( ) ; It1 != data.end( ) ; It1++ )
cout << " " << *It1<<endl;
}
//Usage for C++ class templates
void main()
{
MyQueue<int> q;
q.Add(1);
q.Add(2);
cout<<"Before removing data"<<endl;
q.Print();
q.Remove();
cout<<"After removing data"<<endl;
q.Print();
}
我认为这页面 [ ^ ]将有助于对其进行解释.
I think this page[^] will help to explain it.
这篇关于C ++模板参数化构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!