C++中的getter/setter是正确的方法
Getter/setter in c++ is this the right way?
我做了一个小程序并且可以工作,但我不知道这是否是正确的方法,尤其是对于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);
};
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 为什么我的 setter 方法会产生错误的访问错误
- 在不编写显式 setter 的情况下修改私有类数据成员的便捷方法是什么?模板有用吗?
- 枚举器 C++ 的 setter 和 getter 方法
- 如何在 setter 方法中设置 boost::optional 成员变量的值?
- 在Thrift中,有没有一种方法可以避免生成C++setter
- getter和setter方法的用途是什么
- 当setter方法参数是C++中的引用时会发生什么
- 除了 setter 和 getter 之外的任何其他方法,它们将执行相同的功能但更好
- C++中的getter/setter是正确的方法
- 我应该如何处理只能由工厂类使用的setter方法
- Setter不在类方法内部工作
- 在boost local_date_time中没有setter方法
- 强制类方法使用自己私有成员的setter/getter
- 如何重构冗余的getter/setter方法
- Will编译器会在setter方法中自动应用move语义
- 如何在gtest中测试setter方法
- c++中getter和setter方法的包装器
- 运算符重载 - 在 char 数组包装类中实现 C++ setter 的正确方法是什么