在c ++中使用void *函数

时间:2015-02-26 17:57:11

标签: c++

我目前正在学习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;

有没有&#34;清洁&#34;这样做的方法?类似的东西:

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

感谢。

3 个答案:

答案 0 :(得分:1)

您可以将运营商声明为

int & operator[](list_inx_t n);

int operator[](list_inx_t n) const;

并称之为

cout << A[0] << endl;

A[0] = 12;

答案 1 :(得分:1)

如果您正在尝试创建可以存储“任何内容”的列表,那么您需要了解模板。类似的东西:

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

将为您提供您想要的类型安全。

答案 2 :(得分:0)

list_t A;
int * AA = (int *)A;
cout << AA[0] << endl; // or better printf( "%d\n", AA[0] );
AA[0] = 12;
相关问题