在c++中使用void*函数

Using void* functions in c++

本文关键字:void 函数 c++      更新时间:2023-10-16

我目前正在学习c++,我有一个小问题:

我有这样的方法:

void *list_t::operator[](list_inx_t n)
{
    if (/*condition*/)
    {
        /*Some code here*/;
        return NULL;
    }
    void *p;
    /*Some code here*/
    return p; 
}

这是来自主要功能的代码:

list_t A(/*Constructor variables*/);
cout << *(int*)A[0] << endl;
*((int*)A[0]) = 12;
cout << *(int*)A[0] << endl;

有什么"更干净"的方法吗?类似的东西:

cout << A[0] << endl;
A[0] = 12;
cout << A[0] << endl;

谢谢。

如果您试图创建一个可以存储"任何东西"的列表,那么您需要了解模板。大致如下:

template<typename Type>
class list_t {
public:
    Type *list_t::operator[](list_inx_t n)
    {
      ...etc

template<typename Type>
class list_t {
public:
    Type & list_t::operator[](list_inx_t n)
    {
      ...etc

会给你想要的类型安全。

您可以像一样声明运算符

int & operator[](list_inx_t n);

int operator[](list_inx_t n) const;

并称之为

cout << A[0] << endl;
A[0] = 12;
list_t A;
int * AA = (int *)A;
cout << AA[0] << endl; // or better printf( "%dn", AA[0] );
AA[0] = 12;