我有一个派生自包含自己的成员变量的基类的类。为了保持封装的类中的所有内容,我试图找出一种干净的方法来设置此成员变量,同时在同一方法中检索它。这是方法的样子(这是伪代码,可能不会编译):
class Base
{
virtual void MyVirtualMethod(double &output1, Object &output2)
{
// do base class stuff (does not set output1 because it does not need to)...
output2 = whatever;
}
}
class Derived
{
public:
virtual void MyVirtualMethod(double &output1, Object &output2)
{
// do derived class stuff...
m_DerivedMember = whatever;
// do more stuff...
output1 = m_DerivedMember;
output2 = whatever2;
}
private:
double m_DerivedMember;
}
调用代码#1
std::vector<DataPack> dataPack;
for each Base pointer...
{
double output1(100); // some default value
Object output2;
base->MyVirtualMethod(output1, output2);
dataPack.push_back(DataPack(output1, output2));
}
调用代码#2
double output1(100); // some default value
Object output2;
base->MyVirtualMethod(output1, output2);
// do more stuff but does not actually use output1, just output2...
虽然这有效但对我来说似乎并不干净。我想我问自己一个更大的问题是,同时使用相同的方法作为getter和setter是一个好主意吗?谢谢!
答案 0 :(得分:0)
虽然我不推荐这样做,但您可以返回对您的会员的引用,这样您就可以获得/设置操作。这就是std::vector
重载operator[]
的方式。类似的东西:
#include <iostream>
using namespace std;
class Foo
{
int m_;
public:
Foo(int m): m_(m){}
int& get_set()
{
return m_;
}
const int& get_set() const // for const-access
{
return m_;
}
};
int main()
{
Foo foo(10);
cout << foo.get_set() << endl;
foo.get_set() = 20;
cout << foo.get_set() << endl;
// that's why we need the `const` overload of `Foo::get_set`
const Foo cfoo(100);
cout << cfoo.get_set() << endl;
}
答案 1 :(得分:-1)
要回答您的问题,单独的getter和setter是封装的核心。虽然它可以为您节省额外的功能,但它具有更加清晰和安全的功能,可以获得和设置单独的功能。这里有一些经过调整的代码可以更好地理解
class Derived : public Base
{
public:
virtual void MyVirtualMethod(double &output1, Object &output2)
{
// do derived class stuff...
m_DerivedMember = whatever;
// do more stuff...
output1 = m_DerivedMember;
output2 = whatever2;
}
/*
The setter
*/
void setDerivedMember(double m){
m_DerivedMember = m;
}
/*
the getter
*/
double getDerivedMember(){
return m_DerivedMember;
}
private:
double m_DerivedMember;
}
我们可以调用这些函数,如:
Derived d(1.5, string("I'm a string"));
d.setDerivedMember(5.00);
cout <<"Derived Member Value: " d.getDerivedMember()<<endl;
它会输出:
Derived Member Value: 5.00
希望有意义!