gpt4 book ai didi

c++ - 类指针本身有类成员吗?

转载 作者:行者123 更新时间:2023-11-30 05:15:57 25 4
gpt4 key购买 nike

我想弄清楚一些概念

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;
}

您可以 try it out here并看到它会输出数字 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;
}

关于c++ - 类指针本身有类成员吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42886954/

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