gpt4 book ai didi

Android NDK 中的 C++ 模板

转载 作者:搜寻专家 更新时间:2023-10-30 23:48:21 25 4
gpt4 key购买 nike

我正在使用 Android NDK r6 和 Android SDK API 8 (2.2)。

我正在尝试使用模板实现像 std::vector 这样的动态列表,但我在编译的 .o 文件中遇到很多错误。

示例:

error

如您所见,错误是在编译的 .o 文件中产生的,而不是在源文件中产生的。

类定义:

template <class T>
class ArrayList{
private:
int mSize;

public:
/**
* Construye una lista dinámica vacía.
*/
ArrayList ();

/**
* Destructor.
*/
~ArrayList ();

/**
* Añade un elemento a la lista.
*
* @param element
* Elemento.
*/
void add (T element);

/**
* Obtiene un elemento de la lista.
*
* @param index
* Índice del elemento. Rango válido de valores: [0, size()]
* @return Elemento de la posición indicada o NULL si el índice no es válido.
*/
T get (int index);

/**
* Elimina un elemento de la lista.
*
* @param index
* Índice del elemento. Rango válido de valores: [0, size()]
*/
void remove (int index);

/**
* Vacía la lista.
*/
void clear ();

/**
* Consulta el número de elementos de la lista.
*
* @return Número de elementos.
*/
int size ();

/**
* Consulta si la lista esta vacía.
*
* @return true si está vaía, sinó false.
*/
bool isEmpty ();
};

类实现:

template <class T>
ArrayList<T>::ArrayList (){
mSize = 0;
}

template <class T>
ArrayList<T>::~ArrayList (){

}

template <class T>
void ArrayList<T>::add (T element){

}

template <class T>
T ArrayList<T>::get (int index){
T element;
return element;
}

template <class T>
void ArrayList<T>::remove (int index){

}

template <class T>
void ArrayList<T>::clear (){

}

template <class T>
int ArrayList<T>::size (){
return mSize;
}

template <class T>
bool ArrayList<T>::isEmpty (){
return true;
}

类用法:

ArrayList<OtherClass> list;
OtherClass foo;
list.add (foo);

最佳答案

这是模板代码。您没有与普通 C++ 类相同的头文件与 cpp 文件的关系。我通常像这样重组它:

Foo.h:

#ifndef FOO_H
#define FOO_H

template <class T>
class Foo
{
Foo();
};

// Note that the header file INCLUDES the cpp file. This is simply to maintain
// the general .h .cpp file structure, but adapt it to template code, where the
// implementation is supposed to be in the header file and is not compiled.
#include "Foo.cpp"

#endif

Foo.cpp:

// Note that I do NOT include the header here. Also, do NOT compile this file.
// So if you have a makefile, be sure not to include this file in it.
template <class T>
Foo<T>::Foo()
{ }

或者您可以将整个实现粘贴在头文件中,根本没有 cpp 文件。这实际上更有意义,因为您不编译 cpp 文件。阅读更多 here .

关于Android NDK 中的 C++ 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7044598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com