在这种情况下不使用 'protected' 的任何理由(cpp、c++、oop)
any reason not to use 'protected' in this situation (cpp, c++, oop)
#include <iostream>
using namespace std;
class R {
protected:
int a;
public:
int read(void) {
return a;
}
};
class RW : public R {
public:
void write(int _a) {
a = _a;
}
};
int main(void) {
int a;
R *r = (R *)&a;
RW *rw = (RW *)&a;
rw->write(1);
cout << dec << r->read() << endl;
cout << dec << rw->read() << endl;
return 0;
}
我想做一个只能读(classR)的class和一个可以读写(classRW)的class。有什么理由我不应该在 oop 中这样做吗?还有什么理由不在这里使用 'protected' ?
请帮助我,感谢任何回复!
P.S。我不想在两个 class 上定义重复的 'private int a;',因为 'int a in class RW' 的偏移量和 'class RW' 的大小与 'class R' 不同没有了。
any reason not to use the 'protected' here?
protected
成员变量有时不鼓励使用访问 private
成员变量的 protected
成员函数 - 如果你不需要重复的 a
s在 R
中实现 private
。您可以添加一个 protected
成员函数来写入它。
class R {
public:
int read() const { // not `void` and add `const`
return a;
}
protected:
void write(int A) {
a = A;
}
private:
int a;
};
class RW : public R {
public:
void write(int A) {
R::write(A);
}
};
在 R::write
中没有添加任何验证,上面的代码基本上与您的代码相同,但是 a
是 private
.
不过你原来的版本没有错。从这里可以看出:Should you ever use protected member variables? 没有明确的“不,你不应该使用 protected
成员变量”。
有人可能会争辩说,如果它们只是 protected
,就可以继承 class 并将它们视为 public
,如果更改此类成员变量不需要任何验证任何类型的,它们都可以从 public
开始。一个人必须根据具体情况来看待它。
#include <iostream>
using namespace std;
class R {
protected:
int a;
public:
int read(void) {
return a;
}
};
class RW : public R {
public:
void write(int _a) {
a = _a;
}
};
int main(void) {
int a;
R *r = (R *)&a;
RW *rw = (RW *)&a;
rw->write(1);
cout << dec << r->read() << endl;
cout << dec << rw->read() << endl;
return 0;
}
我想做一个只能读(classR)的class和一个可以读写(classRW)的class。有什么理由我不应该在 oop 中这样做吗?还有什么理由不在这里使用 'protected' ? 请帮助我,感谢任何回复!
P.S。我不想在两个 class 上定义重复的 'private int a;',因为 'int a in class RW' 的偏移量和 'class RW' 的大小与 'class R' 不同没有了。
any reason not to use the 'protected' here?
protected
成员变量有时不鼓励使用访问 private
成员变量的 protected
成员函数 - 如果你不需要重复的 a
s在 R
中实现 private
。您可以添加一个 protected
成员函数来写入它。
class R {
public:
int read() const { // not `void` and add `const`
return a;
}
protected:
void write(int A) {
a = A;
}
private:
int a;
};
class RW : public R {
public:
void write(int A) {
R::write(A);
}
};
在 R::write
中没有添加任何验证,上面的代码基本上与您的代码相同,但是 a
是 private
.
不过你原来的版本没有错。从这里可以看出:Should you ever use protected member variables? 没有明确的“不,你不应该使用 protected
成员变量”。
有人可能会争辩说,如果它们只是 protected
,就可以继承 class 并将它们视为 public
,如果更改此类成员变量不需要任何验证任何类型的,它们都可以从 public
开始。一个人必须根据具体情况来看待它。