在我的特定情况下,我有一个基类“Base”,它有一个数据成员“A_var”。我希望任何派生类都只能以与“基”类语法相同的方式访问该数据成员。
如果它是 protected 或私有(private)的,则派生类分别具有完全访问权限或无访问权限。我可以将其设为私有(private),并创建一个返回 const 引用的 protected 函数,但这样访问在语法上会有所不同。
class Base {
protected:
const type_t& A() const {return A_var;}
private:
type_t A_var;
void f();
};
class Derived : public Base{
public:
void g();
};
//access in Base class
void Base::f() {
type_t value = A_var;
A_var = value;
}
//access in Derived class
void Derived::g() {
type_t value = A();
A() = value; //Error, const reference; good
}
重载“A()”(如下所示)也不起作用,因为“派生”类调用私有(private)非常量“A()”。
protected:
const type_t& A() const {return A_var;}
private:
type_t& A() {return A_var;}
微小的差异可能看起来没什么大不了的,但在我的代码中有各种以访问该数据成员开头的宏。因此,我必须为“基”类和派生类使用不同的宏,这会扰乱代码的读取和写入流程。
更新: 澄清一下,问题之一是使派生类和基类中的访问在语法上相同。也就是说,例如,我可以调用一个函数 f(),并让它在基类中调用时返回一个非 const 引用,而在派生类中调用时返回一个 const 引用。动机是使派生类中的强制 const 访问变得无缝。我意识到可能没有办法做到这一点,但我问以防万一。
更新: 举一个真实的例子(有 2-3 个这样的例子),这在代码中被大量使用:
test_files_var.current()->current_test()
我把它换成了
#define TEST() test_files_var.current()->current_test()
因为派生类将通过不同的函数/成员访问 test_files_var
,即 testFiles()
,所以我必须有 TEST() 的第二个定义
,即 DTEST()
。问题更多是由“宏”的使用次数决定的,而不是由它们的数量决定的。
最佳答案
哪里没有简单的内置解决方案。 但是一点模板魔术可能会有所作为:
template <class NonConst>
struct Matcher {
template <class AnyOther>
static const AnyOther &get(AnyOther &obj) { return obj; }
static NonConst &get(NonConst &obj) { return obj; }
};
class Base {
public:
Base() : a_(42) { }
public:
virtual void Fun() {
Matcher<Base>::get(*this).A();
}
const int &A() const {
std::cout << "const" << std::endl;
return a_;
}
int &A() {
std::cout << "no const" << std::endl;
return a_;
}
private:
int a_;
};
class Derived : public Base {
public:
void Fun() {
Matcher<Base>::get(*this).A();
}
};
int main(int argc, const char * argv[]) {
Derived d;
d.Fun();
Base b;
b.Fun();
return 0;
}
上面的代码会输出:const no const
。
因此,在这两个 Fun
函数中,您基本上具有相同的访问模式,如果需要,您可以将其包装在宏中。
关于c++ - 仅向派生类授予对基类数据成员/函数的常量访问权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34818599/