C++中的getter/setter是正确的方法

Getter/setter in c++ is this the right way?

本文关键字:方法 setter 中的 getter C++      更新时间:2023-10-16

我做了一个小程序并且可以工作,但我不知道这是否是正确的方法,尤其是对于getter,所以这里有一些我的代码,如果你能知道它是严谨还是不严谨,如果有更好的方法来定义setter和getter,那就太好了。

#include"head.h"
int main()
{
    field f("big_field", 20 , 10);
    f.print();
    cout << "Area: " << f.getArea() << endl;
    field t=f;
    t.setPlatums(20);
    t.print();
    cout << "Area: " << t.getArea()<< endl;
    return 0;
}

嗯,这似乎没问题。

#include<iostream>
using namespace std;
class field
{
    string kads;
    int garums;
    int platums;
public:
    void print();
    field(const string& , int,  int);
    int getArea();
    void setPlatums(int);
};

现在对于其他东西和获取器:

#include "head.h"
field::field(const string&t, int a, int b)
{
    kads = t;
    garums = a;
    platums = b;
}
void field::print()
{
    cout << kads << " " << garums << " " << platums << endl;
}
int field::getArea()
{
    return garums*platums;
}
void field::setPlatums(int b)
{
    platums=b;
};

这似乎不是问题,因为代码正在工作,但也许我做错了,我的意思是代码不仅仅是因为它在工作而完全正确。

感谢您的快速回复,很高兴听到我以正确的方式学习,因为很难重新学习错误的方式。

没关系。但是,您应该通过构造函数的初始值设定项列表初始化成员:

field::field(const string&t, int a, int b) :  kads(t), garums(a), platums(b)
{
}

 

另一方面,您可以通过覆盖输出流的运算符<<来替换print

#include <iostream>
class field
{
   .
   .
   .
   friend std::ostream& operator<<(std::ostream& os, const field& f);
};

std::ostream& operator<<(std::ostream& os, const field& f)
{
    os << kads << " " << garums << " " << platums << std::endl;
    return os;
}

 

另一个,尽量不要在头文件中使用 using namespace std;

最后,当您计算getArea中的面积时,您不需要类中的杆件area。 除非您在二传手和回报area上预先计算它。

#include<iostream>
using namespace std;
class field
{
public:
    ...
    // You could implement getters as const functions.
    // int getArea();                
    int getArea() const;
    void setPlatums(int);   
};