1

我在使用 C++ 和嵌套类时遇到了一些问题。例如:

在 main.cpp

int main()
{

B b(par);
cout << b.Aglobal->parametro;
cout << b.Aglobal->parametro;
return 0;}

在 B.cpp

B: B(type par)
{

A a(par1,par2);
Aglobal=&a;}

在 Bh

class B
{
public:
    B(type);
    A *Aglobal;}

在啊

class A
{

public:
    A(type1,type2);
    int parametro;}

main.cpp 的回声不同,我无法理解原因。

4

2 回答 2

3

You define a local variable of type A in the constructor of B, and return a pointer to that local variable. Using that pointer results in undefined behavior, because the object it points to no longer exists.

Solutions to the problem might include:

  • allocate the A object on the heap. But then try to wrap it in an appropriate smart pointer rather than a simple pointer.

  • Have a member of type A in B and return the member's address

  • Have an object of type A with static storage duration, like the pointer itself.

The decision between these three depends heavily on the context of your problem which is not deducible from your question.

One more thing. Nested classes are those classes that are defined in scope of another class. There are no nested classes in your example.

于 2012-05-20T11:38:53.087 回答
0

在 B 构造函数中,您正在保存局部变量的地址。有几种方法可以解决此问题,正确的方法取决于您要对 A 做什么。

此外,您没有嵌套类。嵌套类在另一个类中定义,如下所示:

class OuterClass {
    class InnerClass {
        //class members
    };

    //class members
};
于 2012-05-20T11:39:50.047 回答