当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - scope of classes

问题描述:

class a

{

private:

b *b_obj;

public:

void set(int);

};

a::a()

{

b_obj = new b;

}

a::set(int s)

{

b_obj->c = s;

}

class b

{

public:

int c;

};

is this code valid?

if no, how do i make b_obj of a particular object (say a_obj) of class a ,modifiable in another class c...if a_obj i created in another class d....i am scared of a_obj going out of scope in class c.

hope you understand my question.

thanks a lot for taking the time to read my post

网友答案:

The code is nearly valid. class b needs to be declared (or at least forward declared) before it is referred to in class a, you do not specify the return type in the definition for a::set, and you have not provided a declaration for a'a default constructor. Here is the revised code, along with a test harness:

class b
{
  public:
    int c;
};

class a
{
  private:
    b *b_obj;
  public:
    a();
    void set(int);
};

a::a()
{
  b_obj = new b;
}

void a::set(int s)
{
  b_obj->c = s;
}

int main()
{
    a my_a;
    my_a.set(42);
}

Now, just because the code is valid doesn't mean it's good:

  1. You don't initialize c when default-constructing b.
  2. You use raw pointers to dyanamically-allocated b's. Use automatic variables instead, whenever possible. Among the the reasons for this are ...
  3. You never delete the b you new'ed in a'a constructor. This results in a memory leak. If you had avoided the use of dynamic allocation in the first place, this would not be an issue.
网友答案:

Well,

*b_obj = *other_b_obj;// equality of objects values
b_obj = other_b_obj; // equality for pointer values

assuming that b_obj is an object and other_b_obj is a pointer:

b_obj = *other_b_obj;

Assuming the reverse:

b_obj = &other_b_obj;

Assuming both are pointers:

b_obj = other_b_obj;

for your final question, new is not compulsory for assgining pointers. A pointer may point to an exiting object. However, if you want the pointer to point to a new object, use then new keyword, which attempts to create new object and returns the new object address.

网友答案:

is this code valid?

The code is almost valid, except that you forgot to state the return type of the set function:

void a::set(int s)

However, the set function will really change the c member of b_obj. It is public, so the compiler will allow it.

BTW, why don't you try for yourself?

As an aside, while you're studying, look at constructors, destructors, assignment operator and implement them to free the object b_obj properly. You can even use a shared_ptr for that.

Also, I wouldn't advise you to use such a dull name as lowercase a for a class.

分享给朋友:
您可能感兴趣的文章:
随机阅读: