【问题标题】:Problems with dereferencing a class member pointer that points to another class [closed]取消引用指向另一个类的类成员指针的问题[关闭]
【发布时间】: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


【解决方案1】:

您可以通过以下方式解决它:

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

【讨论】:

  • 就是这样。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-09
  • 1970-01-01
  • 1970-01-01
  • 2018-03-24
  • 1970-01-01
  • 2013-09-05
  • 1970-01-01
相关资源
最近更新 更多