如何使用构造函数代替setter成员函数

时间:2015-11-29 18:29:48

标签: c++ visual-studio-2015

我的程序基本上依赖于setter来初始化我的对象实例中的数据,但是我想删除它们并使用构造函数代替setter,有没有办法可以做到这一点,或者有人可以为我提供参考吗?

实例化对象

//Using SDL and standard IO
#include <SDL.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <iomanip>
#include <archer.hpp>
#include <ctime> 
#include <ArmouredArcher.hpp>
#include <RNGI.hpp>

    using namespace std; //Declaring use of namespace std

    void instantiateMuskateer();

int main(int argc, char* argv[])
{
    //init muskateer object
    instantiateMuskateer();
    system("pause");
    return 0;
}

实例化,活动和销毁

void instantiateMuskateer()
{
    Archer* Muskateer = new Archer();

    Muskateer->setName("Brett"); 

    delete Muskateer;
}

.hpp文件

#ifndef _Archer_
#define _Archer_

#include <string>

class Archer
{
public:
    inline Archer() :
        name(""),
        healthpoints(0),
        baseDamage(0),
        range(0)
        { ; } //All Member varials are in a known state

    inline Archer(std::string name, int healthpoints, int baseDamage, int range) :
        name(name),
        healthpoints(healthpoints),
        baseDamage(baseDamage),
        range(range) //All member variables are in a known state
    {
        ;
    }

    inline ~Archer() { ; } // empty destructor

    inline std::string getName() { return name; }
    inline void setName(std::string name) { this->name = name; }

    inline int getHealthPoints() { return healthpoints; }
    inline void setHealthPoints(int healthpoints) { this->healthpoints = healthpoints; }

    inline int getBaseDamage() { return baseDamage; }
    inline void setBaseDamage(int baseDamage) { this->baseDamage = baseDamage; }

    inline int getRange() { return range; }
    inline void setRange(int range) { this->range = range; }

    /*std::string getName(); //getter for name
    void setName(std::string name); //Set the name

    int getHealthPoints();
    void setHealthPoints(int healthpoints);

    int getBaseDamage();
    void setBaseDamage(int baseDamage);

    int getRange();
    void setRange(int range); */
protected:
private:
    // copy constructor
    Archer(const Archer& other) = delete;
    // overload assignment operator
    Archer& operator=(const Archer& other) = delete;

    std::string name;
    int healthpoints;
    int baseDamage;
    int range;
};

#endif 

1 个答案:

答案 0 :(得分:1)

在您的示例中,它非常简单,您只需要在构造函数中获取所需的参数:

Archer(std::string n) :
        name(n),
        healthpoints(0),
        baseDamage(0),
        range(0)
        {} //All Member varials are in a known state

然后你就可以做到这一点:

void instantiateMuskateer()
{
    Archer* Muskateer = new Archer("Brett");

    delete Muskateer;
}

一些评论没有关系,但改进了你的代码。当您在类中声明并实现函数时,编写inline是无用的,inline是隐含的。此外,如果析构函数不执行任何操作,则不应定义它或使用= default,这样就可以从编译器中启用一些优化。

此外,在您之前的函数中,我发现不需要在堆上分配对象,它再次失去性能和错误源(例如忘记delete对象),分配它堆栈:

void instantiateMuskateer()
{
    Archer Muskateer("Brett");
    // do your things
}

或使用unique_ptr