我想知道如何最好在C++中创建一个数据实体,其中"setter“是私有的,而"getter”是公共的。也就是说,实体的创建者应该能够设置数据,但是用户/使用者/客户端只能获得数据。
让我们考虑实体EntityX:
class EntityX
{
public:
EntityX(int x, int y) : x(x), y(y)
{}
int GetX() const {return x;}
int GetY() const {return y;}
private:
int x,y; // Effective C++ third edition, Item 22: Declare data members private
}
以及创建实体并将其返回给客户端的类方法:
const shared_ptr<EntityX> classz::GetEntityX()
{
shared_ptr<EntityX> entity(new EntityX(1,2));
return entity;
}
在我看来,这使得setter是私有的,getter是公开的,但是如果数据成员大于5-10,这个示例是不实用的.如何使实体类/结构使setter为“私有”,而"getter“为"public",而不使构造函数接受所有数据成员变量。
提前感谢
发布于 2014-05-01 21:24:20
如何将您的创建者设置为friend
为class EntityX
class EntityX
{
friend class Creator;
public:
EntityX(int x, int y) : x(x), y(y)
{}
int GetX() const {return x;}
int GetY() const {return y;}
private:
int x,y; // Effective C++ third edition, Item 22: Declare data members private
};
更新:
或者您可以使用临时友人船,请参阅下面的代码:
#include <iostream>
#include <memory>
template<class T>
class EntityX
{
friend T;
public:
EntityX(int x, int y) : x(x), y(y) {}
int GetX() const {return x;}
int GetY() const {return y;}
private:
int x,y; // Effective C++ third edition, Item 22: Declare data members private
};
struct Creator
{
static const std::shared_ptr<EntityX<Creator>> create()
{
std::shared_ptr<EntityX<Creator>> entity = std::make_shared<EntityX<Creator>>(1,2);
entity->x = 1;
entity->y = 2;
return entity;
}
};
int main()
{
std::shared_ptr<EntityX<Creator>> const E = Creator::create();
std::cout << E->GetX() << ", " << E->GetY() << std::endl;
return 0 ;
}
发布于 2014-05-01 21:26:17
你的得奖者可能会给你一个康斯特&所以.
public:
int const& Getter();
private:
int const& Setter(int value);
用"setter“和"getter”替换为变量的名称。所以..。
public:
int const& X();
private:
int const& X(int value);
你也可以用这个语法写同样的东西..。
const int& X();
只是一个你想怎么写的问题。
祝你好运希望我能帮上忙。
发布于 2014-05-01 21:34:11
不如这样吧:
struct EntityValues
{
Type1 value1_;
Type2 value2_;
(etc for all the members of Entity
};
class Entity
{
public:
Entity () : <set default values>
{
}
// this avoids the sea-of-parameters problem by bundling the data values
// into a single parameter. Data can be added to values by name in random order
// before it is finally used here.
Entity(const EntityValues & values) : <set members by pulling data from values>
{
}
// individual public getters.
Type1 getValue1()const { return value1_;}
<repeat as necessary for other members>
// get everything at once
// (an alternative to individual getters)
//
void exportValues(EntityValues & values) const
{
<copy member to values>
}
// optional (this violates the "no public setters" constraint
// but it does it in a controlled manner.
void update(const EntityValues & values)
{
<set members by pulling data from values>
}
private:
<setters (if necessary) and members go here
};
此外,EntityValues
也可以是在Entity
(即struct Entity::Values
)中声明的公共嵌套结构。
https://stackoverflow.com/questions/23416683
复制相似问题