类指针本身有类成员吗?

do class pointers themselves have class members ?

本文关键字:成员 指针      更新时间:2023-10-16

我想清除一些概念

1-指针只能存储一个地址,指针本身不能像任何其他变量那样存储数据,对吧?(因为下面的代码没有运行(

int *myptr;
*myptr=20;
cout<<(*myptr);

2-如果您创建一个类的指针,例如FOO

class foo
{
public:
  int numb1 ; 
  char alphabet; 
}
// this doesn't run
void main()
{
   foo *myptr ; 
   cout<< myptr->numb1;     
}

所以我的问题是类 foo (*myptr( 的指针会有变量 numb1alphabet 吗? 如果不是,那么 Foo 指针和 int 指针有什么区别(除此之外,每个指针只能指向它各自的数据类型(

指针具有足够的存储空间来包含表示内存中位置的数字。完全可以使用此空间来存储其他信息(信息仍然需要适合指针的存储(。

例如,您可以在指针中存储一个长整型值:

#include <iostream>
using namespace std;
int main() {
    void *ptr;
    ptr = (void*)20;
    long information = reinterpret_cast<long>(ptr);
    std::cout<<information<<std::endl;
    return 0;
}

你可以在这里尝试一下,看看它会输出数字 20。


编辑:这里有一个非空类型的指针

#include <iostream>
using namespace std;
struct test{int a;};
int main() {
    // your code goes here
    test* ptr;
    ptr = (test*)20;
    long information = reinterpret_cast<long>(ptr);
    std::cout<<information<<std::endl;
    return 0;
}