C++ 取消引用指向另一个类的类成员指针时出现问题
我定义了两个简单的类。第一个类(A)包含指向第二个类(b)的对象的指针(b_ptr),第二个类(b)包含一个int成员(i)。我创建了第一个类的对象,我只是想返回指针对象中包含的int 起初我甚至无法编译代码,但后来我移动了C++ 取消引用指向另一个类的类成员指针时出现问题,c++,pointers,declaration,definitions,C++,Pointers,Declaration,Definitions,我定义了两个简单的类。第一个类(A)包含指向第二个类(b)的对象的指针(b_ptr),第二个类(b)包含一个int成员(i)。我创建了第一个类的对象,我只是想返回指针对象中包含的int 起初我甚至无法编译代码,但后来我移动了inta::returnInt()定义,使其位于类B定义之后。我现在可以编译了,但是当我打印对returnInt()的调用时,我得到了一个很大的数字(每次运行时都会改变) 非常感谢您的帮助 // HelloWorld.cpp : main project file. #inc
inta::returnInt()
定义,使其位于类B
定义之后。我现在可以编译了,但是当我打印对returnInt()
的调用时,我得到了一个很大的数字(每次运行时都会改变)
非常感谢您的帮助
// HelloWorld.cpp : main project file.
#include "stdafx.h";
using namespace System;
#include <iostream>
#include <string>
#include <vector>
using namespace std;
using std::vector;
using std::cout;
using std::endl;
using std::string;
class B;
class A {
public:
A() = default;
B* b_ptr;
int returnInt();
};
class B {
public:
B() : i(1){};
A a;
int i;
};
int A::returnInt() { return (b_ptr->i); };
int main()
{
A myClass;
cout << myClass.returnInt() << endl;
}
//HelloWorld.cpp:主项目文件。
#包括“stdafx.h”;
使用名称空间系统;
#包括
#包括
#包括
使用名称空间std;
使用std::vector;
使用std::cout;
使用std::endl;
使用std::string;
乙级;;
甲级{
公众:
A()=默认值;
B*B_ptr;
int returnInt();
};
B类{
公众:
B():i(1){};
A A;
int i;
};
returnInt(){return(b_ptr->i);};
int main()
{
我的班级;
cout您可以通过以下方法解决此问题:
#include <iostream>
using namespace std;
struct B
{
B() : i(1){}
int i;
};
struct A
{
A(B& b) : b_ptr(&b) {}
int returnInt() { return b_ptr->i; }
private:
A() = delete;
B* b_ptr;
};
int main()
{
B b;
A myClass(b);
cout << myClass.returnInt() << endl;
return 0;
}
#包括
使用名称空间std;
结构B
{
B():i(1){}
int i;
};
结构A
{
A(B&B):B_ptr(&B){}
int returnInt(){return b_ptr->i;}
私人:
A()=删除;
B*B_ptr;
};
int main()
{
B B;
A级(b级);
难道你的b_ptr是悬空的-它从来没有指向类型b的有效对象。就是这样。谢谢你的帮助!!