为什么我们需要将const放在函数头的末尾但是首先是静态的?

问题描述 投票:9回答:7

我有这样的代码......

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()也属于同一类。我只是想知道这背后的原因是什么?

c++
7个回答
13
投票

使用int get_hours() const;等const实例方法,const意味着int get_hours() const;的定义不会修改this

使用静态方法,如static void fun();,const不适用,因为this不可用。

您可以从类或实例访问静态方法,因为它的可见性。更具体地说,您不能从静态方法调用实例方法或访问实例变量(例如xhours),因为没有实例。

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;
};

11
投票

最后的const意味着函数是常量,因此它不会改变对象的状态。

当你将const放在最后时,你无法改变对象成员的状态。

声明一个函数static意味着它根本不属于该对象,它属于类类型。

将const放在开头意味着返回类型值是常量。


4
投票

当你将const放在开头时,你将它应用于返回类型。如果你是返回类型,如果无效,这无关紧要,但是让我们说你要返回不是const的char*。如果你把const放在开头,你最终会得到

static const char* MyFunction() { ... }

这告诉我返回类型是const char*,而不是返回char*的const函数。

把它放在最后避免了这个问题。


2
投票

这是因为如果你把const放在第一位就意味着你从函数中返回一个const的东西 - 即函数是const的另一个意思


1
投票

这是一个纯粹的语法问题。 const是一个cv-qualifier,当应用于成员函数时,必须放在参数声明之后。您试图将它放在函数名称之前,它只能被解释为限定函数的返回类型。

另一方面,static是一个存储类说明符,必须出现在它适用的声明符之前。

这些规则只是从定义C ++语法的方式开始。


1
投票

这是因为如果你把const放在第一位就意味着你要从函数中返回一个const的东西


0
投票

here详细解释了一个和另一个。在函数声明之后放置const会使函数保持不变,这意味着它不能改变包含该函数的对象中的任何内容。

© www.soinside.com 2019 - 2024. All rights reserved.