简体   繁体   中英

how to pass a constructor parameter of a class in a different class main in C++

//Class1 main

int main()
{
    ...

    Class1 obj1(parameters);
    Class1 obj2(parameters);    
    Class1 *Array[2];
    Array[0] = obj1;
    Array[1] = obj2;

    Class1 *Pointer = Array;

    Class2 repository(Pointer);   //where the error occurs.
}

obj1 and obj2 were created before and are class1 objects. class2 is a data repository class (Class2) I am trying to pass the array to it to point to it from Class2.

#include "Class2.h"
//what Class2 constructor looks like.

Class2::Class2(Class1* Pointer)
{
    tPointer = Pointer;
}

the problem is that I get an error saying Undefined symbols: "Class2::Class2(Class1*)", referenced from: _main in Class1 ld: symbol(s) not found

Any help would be much appreciated thanks.

You have quite a few errors, I'll try to show you how to fix them.

int main()
{
    ...

   Class1 obj1(parameters);
   Class1 obj2(parameters);    
   Class1 *Array[2];
   Array[0] = &obj1; // Array holds pointers to Class1, so you need to use &
   Array[1] = &obj2; // Here too.

   Class1 *Pointer = Array[0]; // Use Array[0] or Array[1] here

   Class2 repository(Pointer);   //Should be okay now
}

Summary:

In the line Array[0] = obj1; you are forgetting the address operator (same for next line).

The line Class1 *Pointer = Array; doesn't make sense because Array by itself is a pointer to a pointer, you want either Array[0] or Array[1] to make Pointer point at either obj1 or obj2.

Ok so a few things:

1) Array is not type of Class1* it's of Class1**
2) You are making an array of pointers, obj1 and obj2 are not pointers at the moment! either dynamically allocate them or use the & operator to grab the address.
3) This is a suggestion: Use std::vector if possible. Working with pointer arrays can be a pain and get messy real fast.
But if you insist then go right ahead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM