【问题标题】:Getter/setter in c++ is this the right way?c ++中的getter/setter是正确的方法吗?
【发布时间】:2015-02-07 11:50:33
【问题描述】:

我做了一个小程序,它可以工作,但我不知道它是否是正确的方法,尤其是使用 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;
};

这似乎不是问题,因为代码正在运行,但也许我做错了,我的意思是代码并不总是正确的,只是因为它正在运行。

感谢您的快速响应,很高兴听到我正在学习正确的方法,因为很难重新学习错误的方法。

【问题讨论】:

  • 两个 cmets: 1. 如果您从不使用 int area,为什么还要使用它? 2. 确保正确缩进你的代码。
  • 您应该将其发布在 CodeReview 上。你会得到对你更有用和更有趣的答案。例如:你不关心const 的正确性。
  • 这种方法对我来说似乎有效。

标签: c++ getter


【解决方案1】:
#include<iostream>

using namespace std;

class field
{

public:
    ...

    // You could implement getters as const functions.
    // int getArea();                
    int getArea() const;

    void setPlatums(int);   
};

【讨论】:

    【解决方案2】:

    没关系。但是,您应该通过构造函数的 initializer-list 来初始化成员:

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

     

    另一方面,您可以通过覆盖运算符&lt;&lt; 来替换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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-05
      • 1970-01-01
      相关资源
      最近更新 更多