![](/img/trans.png)
[英]Is there a way to call member's getter/setter in C++ without parentheses?
[英]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;
};
这似乎不是一个问题,因为代码工作,但也许我做错了,我的意思是代码并不总是正确的,因为它是有效的。
感谢快速反应,很高兴听到我正在学习正确的方法,因为很难重新学习错误的方法。
没关系。 但是,您应该通过构造函数的initializer-list初始化成员:
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
。 除非你在setter和返回area
预先计算它。
#include<iostream>
using namespace std;
class field
{
public:
...
// You could implement getters as const functions.
// int getArea();
int getArea() const;
void setPlatums(int);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.