【发布时间】:2009-05-08 07:48:25
【问题描述】:
这是一个完整的例子。 我想通过只允许转换来禁止使用从 B 转换到 A 的对象的 A::set B 到常量 A。 怎么做? (我不能使用虚函数)
#include <iostream>
#include <cassert>
using namespace std;
class A {
public:
int get() const { return i_; }
void set(int i) { i_ = i; }
protected:
int i_;
};
class B : public A {
public:
int ok() const { return A::get() == copy_i_; }
void set(int i) { A::set(i); copy_i_ = i; }
protected:
int copy_i_;
};
void test2() {
A a;
a.set(3); // ok here
cout << a.get() << endl;
B b;
b.set(5);
A& aa = b;
assert(b.ok());
aa.set(3); // not ok here
assert(b.ok()); // fail-here
}
int main() {
test2();
return 0;
}
【问题讨论】:
标签: c++ inheritance constants