【发布时间】:2014-08-04 00:46:48
【问题描述】:
我定义了两个简单的类。第一个类 (A) 包含一个指向第二个类 (B) 的对象的指针 (b_ptr),该对象包含一个 int 成员 (i)。我创建了第一个类的对象,只是试图返回指针对象中包含的 int。
起初我什至无法编译代码,但后来我移动了int A::returnInt() 定义,使其位于class 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;
}
【问题讨论】:
-
您的 b_ptr 悬空 - 它从未指向 B 类型的有效对象。
标签: c++ pointers declaration definitions