C++实现文件中的 Getter-Setter

发布于 2024-11-27 19:37:00 字数 570 浏览 4 评论 0原文

我对 C++ 比较陌生,我认为通过示例可以最好地理解我的问题。在我的头文件中,假设我有

class myClass{
    public:
        double getVar1();
        void setVar1(double newVar1);
        void copyVar1(myClass* dat);

    private:
        double var1;
};

在我的实现 .cc 文件中,当实现 copyVar1 方法时,我应该这样做,

void myClass::copyVar1(myClass* dat){
   var1 = dat->var1;
}

或者

void myClass::copyVar1(myClass* dat){
   var1 = dat->getVar1();
}

在第二种情况下,我使用 getter 方法。两者都可以在 Visual C++ 中正常工作,但我想知道在实践中哪个更好。

谢谢您的评论!

I'm relatively new to C++ and I think that my question may be understood best by example. In my header file, suppose I have

class myClass{
    public:
        double getVar1();
        void setVar1(double newVar1);
        void copyVar1(myClass* dat);

    private:
        double var1;
};

In my implementation .cc file, when implementing the copyVar1 method, should I do

void myClass::copyVar1(myClass* dat){
   var1 = dat->var1;
}

or

void myClass::copyVar1(myClass* dat){
   var1 = dat->getVar1();
}

where in the second case, I use the getter method instead. Both work properly in Visual C++, but I would like to know which is better to use in practice.

Thank You for your comments!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

大姐,你呐 2024-12-04 19:37:00

最佳实践?重载赋值运算符而不是编写方法。

myClass & myClass::operator=(const myClass & dat)
{
   var1 = dat.var1; // or dat.getVar1()
   return *this;
}

至于使用场地还是叫二传……这都是个人喜好的问题。如果你的 getter 有一些副作用,那么你可能应该调用它,否则,使用该字段。

所以,一个很大的“取决于”。

Best practices? Overload the assignment operator instead of writing a method.

myClass & myClass::operator=(const myClass & dat)
{
   var1 = dat.var1; // or dat.getVar1()
   return *this;
}

As for using the field or calling a setter... it's all a matter of personal taste. If your getter has some side effect, then you probably should call it, otherwise, use the field.

So, a big "depends".

李白 2024-12-04 19:37:00

当您在类之外时,您几乎应该始终使用 getter/setter 方法来访问变量,而且通常您必须这样做,因为这是唯一的方法。但是,当您在类内部时,您可以使用其中任何一个,并且如果 getter 方法除了返回变量之外什么也不做,则不会产生任何影响。

您的决定将取决于 getter 方法中的代码是否不仅仅执行返回变量的操作,以及您是否希望在调用 copyVar1 时运行该代码< /强>。如果您不知道,我的建议是,如果您将来决定更改其中的代码,仍然使用 getter 方法。虽然现在直接访问它就可以正常工作,并且您可能会获得微观上更好的性能,但是更容易发现在不应该调用 getter 时调用 getter 的错误,在应该调用 getter 时却没有调用它的错误。编译器最终可能会进行足够的优化,以至于您甚至感觉不到差异。 :D

You should nearly always use getter/setter methods to access a variable when you're outside of the class, and often you have to because that's the only way to do so. However, when you're inside the class you can use either, and if the getter method does nothing but return the variable it won't make a difference.

Your decision is going to be based on if you have code in the getter method that does something more than just returning the variable, and if you want that code to be run when copyVar1 is called. If you don't know, my advice would be to still use the getter method should you ever decide to change the code in it in the future. While it works fine now just accessing it directly, and you might have microscopically better performance, it will be much easier to find an error of calling the getter when you shouldn't that not calling it when you should. And the compiler will probably end up optimizing enough that you won't even feel the difference. :D

轮廓§ 2024-12-04 19:37:00

我更喜欢使用 setter 和 getter 这种方式,如果你改变一些实现细节(例如引入对值分配的验证),你必须在 setter 的一个地方改变它......

I would prefer using setters and getter that way if way your change some implementation details (for example introduce validation on value assign) you jest have to change that in one place in setter...

赴月观长安 2024-12-04 19:37:00

这取决于。许多人会告诉您,使用 getter/setter 代替变量对于编程错误和更改更稳健,并减少代码重复。但是,只要这些 getter/setter 不是内联函数,您可能会受到较小的性能影响,并且由于实现必须了解类的内部结构,为什么不直接使用变量呢?

It depends. Many people will tell you that using the getters/setters instead of the variables is more robust to programming errors and changes and reduces code duplication. But as long as these getters/setters are no inline functions you may get a small performance hit and as the implementation has to know the class's internals anyway, why not just use the variables directly.

对不⑦ 2024-12-04 19:37:00

你想写一个复制构造函数吗?当你有 setVar1 时,为什么还需要 copyVar1 ?如果您尝试编写复制构造函数,最好不要使用 getter。

myclass(const myclass& other)
{
var1 = other.var1;
}

当你同时拥有 getter 和 setter 时,为什么不将 var1 公开呢?

Are you trying to write a copy constructor? Why do you need copyVar1 when you have a setVar1? If you are trying to write a copy constructor, it is better not to use getter.

myclass(const myclass& other)
{
var1 = other.var1;
}

When you have both getter and setter, why not make the var1 public?

皇甫轩 2024-12-04 19:37:00

这里没有正确或错误的方法。

但是,您假设 getVar1() 返回值或 var1。如果您决定更改 var1 值的存储方式,那么您需要检查所有代码并更新它。使用 setter / getter 将其简化为几个方法。在这种情况下,您应该使用第三个选项:

void myClass::copyVar1(myClass* dat){
   setVar1 (dat->getVar1());
}

然后完全删除对 var1 的依赖,您可以将 var1 更改为其他内容,并且 copyVar1 仍然可以工作。

There is no right or wrong way to do it here.

However, you are assuming that getVar1() returns the value or var1. If you decide to change the way the var1 value is stored then you need to go through all the code and update it. Using a setter / getter reduces this to just a couple of methods. In which case, you should use a third option:

void myClass::copyVar1(myClass* dat){
   setVar1 (dat->getVar1());
}

and then you completely remove the dependency on var1, you can change var1 to something else and the copyVar1 will still work.

俏︾媚 2024-12-04 19:37:00

正如你所说,两者都可以正常工作并且完全合法。

从某种意义上说,直接访问成员变量或使用访问器之间的区别在于,您在类内部定义了更强大的“层”;该层与任何层一样,可以帮助您减少依赖性。

换句话说,getter 方法基本上满足了不向外界公开实现细节的要求;比如说,有一天您可能决定不将 var1 存储为双精度型,而是计算它。因此,访问器为您提供了这种自由:在一定程度上您可以更改实现而不影响其他类(即减少依赖性)。

在类本身内使用 getter 方法的情况也是如此,即,您正在删除类范围内的依赖项,并且您的设计对更改更具弹性。

As you say, both work correctly and are perfectly legal.

In a sense the difference between accessing directly the member variable or using an accessor is that you define a stronger "layer" inside of your class; this layer, as any layer, helps you reducing dependencies.

In other words, a getter method responds basically to the requirement of not disclosing to the outside world an implementation detail; say, you might decide one day that instead of storing var1 as a double, you calculate it. So, the accessor gives you this kind of freedom: to an extent you can change the implementation without affecting other classes (i.e., reducing dependencies).

The same is true in the case of using the getter method within the class itself, i.e., you are removing dependencies within the class scope and your design is more resilient to changes.

方圜几里 2024-12-04 19:37:00

setter 和 getter 抽象的一点是检索方法可能会改变。当您直接访问成员变量时,如果有任何变化,您必须在各处更新您的用法。但如果您使用该函数,则只需在函数中更改变量的检索方式即可。

现在,因为这是同一个类,所以与将变量公开时相比,问题要少得多,因为您只需更新这个实现文件(而不是更新类的每个用户,如果您这样做,这可能是不可能的)有图书馆课)。

要了解这一点,请查看突然需要设为线程安全的类。现在,

void myClass::copyVar1(myClass * dat)
{
    scoped_lock lock(mutex);
    var1 = dat->getVar1();
}

如果您始终通过函数调用,您的复印机将看起来像这样,并且您无需修复其他任何地方。如果您直接访问该变量,那么它看起来就像

void myClass::copyVar1(myClass * dat)
{
    scoped_lock lock(mutex);
    scoped_lock lock2(dat->mutex)
    var1 = dat->var1;
}

锁定了 dat 外部的“dat”互斥体,通常不被认为是一个很好的设计(如果您让工程师必须记住锁定其他人的对象,那么您就有机会他们忘记了并且不这样做)。

同样,如果变量开始存储在数据库中,您也必须处理它。或者,如果变量现在存储在两个不同的变量中并在检索时构造,您可以看到复杂性会如何增加。

但请记住,使用访问器和修改器的设计理念是通过封装来降低潜在的复杂性。有时,在处理较小的项目(特别是个人项目)时,您无意更改类。直接访问它们可能不太复杂。不要害怕这样做,只要知道你为什么做出这个决定即可。

The point of the abstraction of setters and getters is that the method of retrieval may change. When you access the member variable directly, then if anything changes, you have to update your usage everywhere. But if you use the function, then changing the way the variable is retrieved only has to change in the function.

Now, because this is the same class, it is much less of a concern than when you make variables public, because you only have to update this one implementation file (instead of updatinng every user of your class, which may not be possible if you have a library class).

To see this, look at a class that suddenly needs to be made thread safe. Now, your copier would look like

void myClass::copyVar1(myClass * dat)
{
    scoped_lock lock(mutex);
    var1 = dat->getVar1();
}

and you would not have to fix anywhere else if you always called by function. If you accessed the variable directly, then it would look like

void myClass::copyVar1(myClass * dat)
{
    scoped_lock lock(mutex);
    scoped_lock lock2(dat->mutex)
    var1 = dat->var1;
}

which locks "dat"s mutex external to dat, usually not considered a very good design (if you make engineers have to remember to lock other people's objects then you open up the chance that they forget and don't do it).

Similarly, if the variable began to be stored on a database, you'd have to handle that as well. Or if the variable now was stored in two different variables and constructed when it was retrieved, you can see how the complexity would increase.

But remember, the design philosophy of using accessors and mutators is to lower potential complexity through encapsulation. There are times when working on smaller projects (particularly personal projects) where you have no intention of ever changing the class. It might be less complex to access them directly. Don't be afraid to do so, just know why you are making the decision.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文