【发布时间】:2017-07-21 14:47:12
【问题描述】:
我是 C++ 新手,我正在尝试通过 char* 返回类中声明的结构。
#include<iostream>
using namespace std;
#include <cstring>
class test
{
public:
struct pair
{
int a,b;
};
test(){
pir=new pair;
pir->a=1;
pir->b=2;
}
void readx(char* str)
{
char* str2=new char[sizeof(pair)+1];
str2=reinterpret_cast<char*>(pir);
strncpy(str,str2,sizeof(pair));
}
private:
pair* pir;
};
int main()
{
test t;
char* ptr;
t.readx(ptr);
cout<<*((int*)ptr)<<endl;
cout<<*((int*)ptr+4)<<endl;
return 0;
}
我尝试了多种方法,但仍然未能返回可以重新解释为结构的 char*。实际上返回的 char* 只能保存第一个参数,丢失有关第二个参数的信息,尽管我使用了 strncpy 函数。此测试代码的输出是
1
0
如何在类中返回关于 struct 的所有内容?
【问题讨论】:
-
strncpy()用于复制以 NUL 结尾的字符串。尝试改用memcpy()。 -
@MikeCAT 我刚试过
memcpy(),但似乎也不起作用。 -
结合了 memcpy 和 +1 的变化,真的很管用!非常感谢!!