Ad

Can I Pass An Array Of A Class That Is Within/or Is A Subcomponent Of An Array Of Classes To A Function In C++?

- 1 answer

Can I pass an array (contactsLonN ..) of a class that is within/or a subcomponent of an array of classes (chainref) to a function in C++?

// ChainNetwork.cpp
void build_contact_map(Chain *chain, int num_chains,Contact *map) {
    //accept 1 of contactsLonN, contactsLonS, contactsLatW, contactsLatE;    
}

// ChainNetwork.h
class Vector {
public:
    double x;
    double y;
    double z;
Vector (); // Constructor declared.
};
inline Vector::Vector() {
    x = 0.0;
    y = 0.0;
    z = 0.0;
}

class Contact {
public:
    int cresid;
    double distance;
    Contact (); // Constructor declared.
};
inline Contact::Contact() {
    cresid = -1;
    distance = 0.0;
}


class ChainNetwork {
public:
    struct Contact contactsLonN[1000][20];
    struct Contact contactsLonS[1000][20];
    struct Contact contactsLatW[1000][20];
    struct Contact contactsLatE[1000][20];
}


// declarations in ChainNetwork.h
void build_contact_map(ChainNetwork *chain, int num_chains,Contact *map);
double distance ( Vector v1, Vector v2 );



// main.cpp main()
ChainNetwork *chainref;
 try {
     chainref = new ChainNetwork [num_chains];
 } catch (std::bad_alloc xa) {
     std::cout << "Allocation Failure\n";
     return 1;
 }

// 1 generic function I would like to call .. but seems to grow uncontrollably if I try to use switch(s)
build_contact_map(chainref,chains_to_use,chainref[i].contactsLonN);
build_contact_map(chainref,chains_to_use,chainref[i].contactsLonS);
build_contact_map(chainref,chains_to_use,chainref[i].contactsLatW);
build_contact_map(chainref,chains_to_use,chainref[i].contactsLatE);

Note: Related results usually employed simpler structures like ints, float, or struct, but not an array or double index array of a class within a class.

Note2: I have made extensive use of functions receiving "Vector" correctly, by reference or address; how about contactsLonN ..

Ad

Answer

Contact[1000][20] cannot be converted to Contact*; they are different types. You could change build_contact_contact_map() to accept Contact (*map)[20], or, better yet, use a std::vector<std::vector<Contact>> instead of raw arrays.

Ad
source: stackoverflow.com
Ad