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

In the B constructor, you are saving the address of a local variable. There are several ways to fix this, the right one depends on what you are trying to do with A.

Furthermore, you do not have a nested class. A nested class is defined inside of another class like this:

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

    //class members
};
于 2012-05-20T11:39:50.047 に答える