为什么我们需要将const放在函数头的结尾,但是首先是静态的? [英] Why we need to put const at end of function header but static at first?

查看:164
本文介绍了为什么我们需要将const放在函数头的结尾,但是首先是静态的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码...

  class Time 
{
public:
Time(int,int,int);
void set_hours(int);
void set_minutes(int);
void set_seconds(int);

int get_hours()const;
int get_minutes()const;
int get_seconds()const;

static void fun();

void printu()const;
void prints();

private:
int x;
int hours;
int minutes;
int seconds;
const int i;
};

为什么我需要将 const 最后一个函数常量类型,但如果我需要一个函数,我可以这样做...

  static void Time :: fun()
{
cout<<hello;
}

上述函数 fun()也在同一类。我只想知道一个const实例方法如这是什么原因是什么?

解决方案

int get_hours()const; const 表示 int get_hours()const; 不会使用静态方法(例如)修改



fun();
,const不适用,因为不可用。



您可以从类或实例中访问静态方法,因为它的可见性。更具体地说,你不能从静态方法中调用实例方法或访问实例变量(例如 x hours 不是实例。

  class t_classname {
public:
static void S(){this- > x = 1; } //<<错误。这在静态方法中不可用
void s(){this-> x = 1; } //< ok
void t()const {this-> x = 1; } //<错误。在const方法中不能改变状态
static void U(){t_classname a; a.x = 1; } //<< ok创建一个实例并在静态方法中使用
void v()const {S(); U(); } //<<好。静态方法对此可见,并且不会改变此。

private:
int a;
};


I have code like this...

class Time
{
    public: 
        Time(int, int, int);
        void set_hours(int);
        void set_minutes(int);
        void set_seconds(int);

        int get_hours() const;
        int get_minutes() const;
        int get_seconds() const;

        static void fun() ;

        void printu() const;
        void prints();

    private:
        int x;
        int hours;
        int minutes;
        int seconds;
        const int i;
};

Why do I need to put const at last to make a function constant type but if i need to make a function, I can do this like...

static void Time::fun() 
{
    cout<<"hello";
}

Above function fun() is also in same class. I just want to know what is the reason behind this?

解决方案

with a const instance method such as int get_hours() const;, the const means that the definition of int get_hours() const; will not modify this.

with a static method such as static void fun();, const does not apply because this is not available.

you can access a static method from the class or instance because of its visibility. more specifically, you cannot call instance methods or access instance variables (e.g. x, hours) from the static method because there is not an instance.

class t_classname {
public:
  static void S() { this->x = 1; } // << error. this is not available in static method
  void s() { this->x = 1; } // << ok
  void t() const { this->x = 1; } // << error. cannot change state in const method
  static void U() { t_classname a; a.x = 1; } // << ok to create an instance and use it in a static method
  void v() const { S(); U(); } // << ok. static method is visible to this and does not mutate this.

private:
  int a;
};

这篇关于为什么我们需要将const放在函数头的结尾,但是首先是静态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆