[英]passing a class as a parameter c++
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: Ben cisneros评论的一个例子如下:
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. 像您描述的那样的功能将自动向上转换对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.