再会,
我不确定如何用一句话正确描述我正在询问的过程,所以请原谅标题。我正在寻找一种方法来确保基类和/或接口的用户会以非默认方式分配对象本身和其他对象会考虑的数据。所以我一直在做以下事情:
struct ExampleInterface {
virtual void SomeMethod() = 0;
virtual std::string WhatLooksLikeAGetterButIsNot() = 0;
};
这是一个真实世界的例子:
//So states can be "poped in and out".//
struct State
{
//To retrive what the active state is called.//
/*Code In Question--->*/virtual std::string RegardStateAs() = 0;/*<---Code In Question*/
virtual void ExecuteState( VRGE::MDNode* metaData ) = 0;
};
这个想法是最终做一些事情,比如 A (如果有人从“更新”派生,这个选项允许试图阻止问题发生):
struct Update : public State
{
//Yadda yadda...//
/*Code In Question--->*/std::string RegardStateAs() {
return std::string{ "Update" };
}/*<---Code In Question*/
};
B(此选项不允许 A 所做的事情):
struct Update : public State
{
//Yadda yadda...//
//Not a good example, but the point gets across.//
Update( std::string value ) {
stateName = value;
}
/*Code In Question--->*/virtual std::string RegardStateAs() {
return stateName;
}/*<---Code In Question*/
private:
std::string stateName;
};
我的问题是:这是好的还是坏的做法?
- - -编辑 - - -:
我无法访问可以编译它的编译器,但是有人向我指出,在这种情况下“覆盖”将是完美的,例如:
//So states can be "poped in and out".//
struct State
{
//To retrive what the active state is called.//
/*Code In Question--->*/virtual std::string RegardStateAs() = 0;/*<---Code In Question*/
virtual void ExecuteState( VRGE::MDNode* metaData ) = 0;
};
struct Update : public State
{
//Yadda yadda...//
/*Code In Question--->*/std::string RegardStateAs() override {
return std::string{ "Update" };
}/*<---Code In Question*/
};