开发者

Object initialization problem in C++ header file

I am coding in C++, and I have private data members in the header file of a class.

private:
      Object1 obj1;
      Object2 obj2(&obj1);

So, the second object takes a pointer to the first object. When I try to compile the program, I get the following error:

"expected identifier before ‘&’ token"

Is there a way to instantiate the objects inside this class' constructor in the implementation file rather than its definition? How do I correct this er开发者_C百科ror? The program won't compile.


In C++, you cannot initialize members as part of the class definition. This kind of operation should be done in the constructor:

myClass() : obj2( & (this->obj1) ) { ... }

This will usually generate a warning, but will be fine as long as obj2 does not use its constructor argument until the construction of myClass is complete.


What your compiler is telling you with this error is that you are trying to make a method called obj2, returning an Object2 that is taking a reference as a parameter. But it can't figure out what the type of the reference is.

On the other hand if you want to set the reference before the construction of the object you can write something like this :

Object2* obj2 = &obj1;

Edit

How do I correct this error? The program won't compile.

Making your program compile is not always the best solution, maybe there is a reason why it won't compile and you have to understand why it is so. Simply correcting the error might not help your cause. As Nawaz pointed out in the comment, if the types Object1 and Object2 are different, it is possible that what you are trying to do is not the right thing.


You cannot write like this:

 Object2 obj2(&obj1);

Use constructor to initialize objects, like this:

class Sample
{
private:
      Object1 obj1;
      Object2 obj2;
public:
     Sample(Object1 o1)  : obj1(o1), obj2(&o1)
     { 
     }
};

Read this to understand this in detail:

http://www.cprogramming.com/tutorial/initialization-lists-c++.html


You can't assign values to members like that in their declaration. You'll have to do that in the class' constructor.

MyClass
{
    private:
        Object1 obj1;
        Object2 obj2;

    public:
        MyClass()
        {
            obj2 = Object2(&obj1);
        }
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜