【发布时间】:2018-12-03 08:38:31
【问题描述】:
我有一个带有模板的独立类,它为某些运算符重载,我想把它作为调用者类的触发器。 示例代码:
独立类
template <typename DataType>
class IndependentClass{
public:
DataType _value;
IndependentClass(){};
IndependentClass(DataType val):_value(val){};
~IndependentClass(){};
IndependentClass& operator=(const IndependentClass<DataType>& mu){
if (this != &mu){
_value = mu._value;
//I want to trigger caller method from here
//But how this class can know the caller class?
// _caller.callParentMethod();
}
return (*this);
}
IndependentClass& operator=(int val){
return (operator=(IndependentClass<DataType>(val)));
}
DataType getValue()const{
return _value;
}
};
基类
class BaseClass{
public:
int sum;
BaseClass(){};
~BaseClass(){};
void setValue(int value){sum+=value;}
int getValue(){return sum;}
};
派生类
Independent 类将在这个类中使用。
//Declare Independent Class
typedef IndependentClass<int> I8;
class DerivedClass : public BaseClass{
public:
I8 sumThisClassValue;
DerivedClass(){
methodDerivedClass();
};
~DerivedClass(){};
void methodDerivedClass(){
sumThisClassValue = 8;
Base::setValue(4);
cout<<"Value = "<<Base::getValue()<<endl; //Output 4
cout<<sumThisClassValue<<endl;
cout<<"Value = "<<Base::getValue()<<endl; //Output that I want is 12
}
void callParentMethod(int _val){
Base::setValue(_val);
}
};
主要
int main(){
DerivedClass objectTLM;
return 0;
}
到目前为止,我正在考虑使用 2 个模板 template<typename DataType, typename Caller> 并在我的独立类中添加另一个构造函数,但我仍然如何传递派生类本身,即 (I8 objA = new I8(this)) *它也不起作用
在真实的代码场景中,我有多个来自同一个基类的派生类,而基类可以监控每个派生类的每个值。
请帮忙。谢谢。
【问题讨论】:
-
它看起来像某种CRTP。但我不确定你想要什么。
-
看来你应该使用组合而不是继承,还要考虑你的设计,这没有多大意义,
getValue适用于sum,而不是sumThisClassValue。 -
编辑您的问题以包含minimal reproducible example。
-
感谢您的建议,我已经稍微修改了代码。
标签: c++ oop templates inheritance