在c++中使用void*函数
Using void* functions in 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;
有什么"更干净"的方法吗?类似的东西:
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;
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 在c++类上调用void函数
- C++为什么尽管我调用了void函数,它却不起作用
- 如何从void函数输出字符串
- 如何将指针从一个void函数传递到另一个C++
- 为什么我在使用void函数时得到错误代码C2276
- 指针没有更新它在void函数内部指向的值
- 为什么我们要为avl树实现返回一个指向节点的指针,而不是void函数
- void 函数可以传递值参数吗?
- 在 void 函数中使用 #include 变量C++
- 如何在 C++ 中将 void 函数传递给 void 指针
- 使用运算符调用 void 函数时出错<set>
- C++ 随机数生成器:尝试将结果作为向量获取,但通过制作 void 函数来执行此操作而出现错误
- C++ :: 如何捕获由 void 函数创建的矩阵
- 如何将一个 void 函数传递给另一个 void 函数?
- 当我使用 void 函数的返回值(通过强制转换函数指针)时,究竟会发生什么?
- C++命名空间中调用 void 函数的错误
- 当数组位于两个循环之间时,您可以调用数组的 void 函数吗?
- 结构新手,我对如何从 void 函数中返回值并将其放入另一个函数感到困惑
- 查找素数:错误:控件到达非void函数的末尾