如何创建类模板数组?

时间:2015-12-19 11:53:10

标签: c++ arrays templates object reference

我需要在C ++中创建一个类模板数组,但编译器不允许它。 示例:

.import __MYMEMSEG_LOAD__, __MYMEMSEG_SIZE__
主要功能

中的

class CRefBase {
public:
    virtual ~CRefBase() = 0;
};

template<class T>
class CRef : public CRefBase {
private:
    T *Obj;
public:
    CRef(T *Obj){ this->Obj=Obj; }
}

我看到了this主题,但这不是我的答案。

由于

3 个答案:

答案 0 :(得分:1)

public class MainActivity extends AppCompatActivity { TextView word; TextView plsenteracharacter; EditText givenchar; Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); word = (TextView)findViewById(R.id.textView); plsenteracharacter = (TextView)findViewById(R.id.textView2); givenchar = (EditText)findViewById(R.id.editText); dene = (Button)findViewById(R.id.button); //Create a dictionary final String [] dictionary = {"home"}; //Create a random number for selecting a random word from dictionary final int rnd = (int)(Math.random()*1); //Take a character from user final String enteredchar = givenchar.getText().toString(); //Selected a random string final String str = dictionary[rnd]; //Make that string a charArray final char[] charArray = str.toCharArray(); //Creating "_" length of the string final char answer[] = new char[str.length()]; int k; for(k=0;k<charArray.length;k++) { answer[k]='_'; } word.setText(answer, 0, k); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int p; for (p=0;p<charArray.length;p++){ if(enteredchar== String.valueOf(charArray[p])){ answer[p] = enteredchar.charAt(0); word.setText(String.valueOf(answer)); } } } }); } } 是一个类模板,CRef是一个(不可实例化的)抽象基类。

你没有按照标题所说的那样做:

  

如何创建模板化类的数组?

哦,你需要一组用于多态的poitnters(以及一个CRefBase基类析构函数):

virtual

就是这样。好好管理动态分配的内存。

答案 1 :(得分:1)

即使您尝试实例化派生类,这也是一个糟糕的主意,因为无法以这种方式对数组进行索引 - 当您使用0以外的任何索引将指针索引到CRefBase时,它们必须只能是CRefBase,并且不能是任何派生类。

此外,在new[]的使用中存在大量异常不安全和内存泄漏,这在所有合理的代码库中都被禁止。使用像std::vector<std::unique_ptr<CRefBase>>之类的东西是安全的,如果你创建一个派生类类型的对象,你实际上可能会创建一个有效的程序。

答案 2 :(得分:-1)

以下代码表示纯虚函数,因此“CRefBase”是一个抽象基类,这意味着它无法实例化!

virtual ~CRefBase()=0;

作为您的问题,模板支持数组。你可以先修复你的编译问题然后重新测试

相关问题