Instead of doing this and keep on making redundant code for everything:
Molecule::Molecule(Hydrogenyx& h){
//some code
}
Molecule::Molecule(Carbonyx& c){
//same code as hydro
}
Molecule::Molecule(Sulphuryx& s){
//same code
}
is there a way I can just make it so it can look like this?:
Molecule::Molecule(x){
//code that can apply to all
}
is there a way I can just make it so it can look like this?:
Sure. You can use a member function template.
Declaration:
template <typename T> Molecule(T& t);
Implementation:
template <typename T>
Molecule::Molecule(T& t){
// The common code.
}
An example of Ben cisneros comment would be the following:
class Example {
// shared code
}
class Hydrogenyx : public Example {
// code for Hydrogenyx
}
With that you can do something like this:
Example* ex;
Hydrogenyx hx(/*Construcr things*/)
ex = &hx;
Functions like the ones you described would automatically up-cast the object.
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.