Вопрос

Hello i want to create a new class variable that is a pointer and initialize it by copy constructor. Though I know how copy constructor works by refernce, i cannot figure out how to do it. Can you help me? For example I have this definition:

class A{
public:
 int a;
private:
};

and in another code segment i do the following:

A *object= new A;
A->a=10;

A *newobject= new A(*object);

but i get a segmentation fault. Can you help me? I also tried:

 A *newobject= new A(&(*object));

but it doesn't work either.

Это было полезно?

Решение 2

With this kind of simple example, the following which uses the default bit wise copy constructor works fine.

The simple class looks like

class Bclass {
public:
    int iValue;
};

And the code to use the copy constructor looks like:

Bclass *pObject = new Bclass;
pObject->iValue = 10;

Bclass *pObject2 = new Bclass (*pObject);

Using Microsoft Visual Studio 2005, the above works fine.

See also Implementing a Copy Constructor.

See also Copy constructor for pointers to objects.

Другие советы

These lines in your example shouldn't even compile:

A *object= new A;
A.a=10;

What you mean is

Foo *object = new Foo;
object->a = 10;

Right?

Edited to add:

What happens when you try the code posted by @Alok Save?

Since the class name is Foo and not A, a Foo object should be created.

class Foo{
  public:
  int a;
  private:
}; 

 Foo *object= new Foo;
 object->a=10;

Now since object is a pointer to class Foo, the -> operator should be used.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top