c ++类成员函数_C ++中类的成员函数

c ++类成员函数

Member functions are the functions, which have their declaration inside the class definition and works on the data members of the class. The definition of member functions can be inside or outside the definition of class.

成员函数是这些函数,它们在类定义中声明它们并在类的数据成员上工作。 成员函数的定义可以在类的定义之内或之外。

If the member function is defined inside the class definition it can be defined directly, but if its defined outside the class, then we have to use the scope resolution :: operator along with class name alng with function name.

如果成员函数是在类定义内定义的,则可以直接定义,但是,如果它是在类外部定义的,则我们必须使用范围解析::运算符以及带有函数名的类名称alng。

For example:

例如:

class Cube
{
    public:
    int side;
    /*
        Declaring function getVolume 
        with no argument and return type int.
    */
    int getVolume();     
};

If we define the function inside class then we don't not need to declare it first, we can directly define the function.

如果我们在类内部定义函数,则无需先声明它,我们可以直接定义该函数。

class Cube
{
    public:
    int side;
    int getVolume()
    {
        return side*side*side;      //returns volume of cube
    }
};

But if we plan to define the member function outside the class definition then we must declare the function inside class definition and then define it outside.

但是,如果我们计划在类定义之外定义成员函数,则必须在类定义内部声明该函数,然后在外部定义它。

class Cube
{
    public:
    int side;
    int getVolume();
}

// member function defined outside class definition
int Cube :: getVolume()
{
    return side*side*side;
}

The main function for both the function definition will be same. Inside main() we will create object of class, and will call the member function using dot . operator.

两个函数定义的主要功能将相同。 在main()内部,我们将创建类的对象,并将使用dot调用成员函数. 操作员。

在C ++中调用类成员函数 (Calling Class Member Function in C++)

Similar to accessing a data member in the class, we can also access the public member functions through the class object using the dot operator (.).

与访问类中的数据成员类似,我们还可以使用点运算符(.)通过类对象访问公共成员函数。

Below we have a simple code example, where we are creating an object of the class Cube and calling the member function getVolume():

下面有一个简单的代码示例,其中我们创建一个Cube类的对象并调用成员函数getVolume()

int main()
{
    Cube C1;
    C1.side = 4;    // setting side value
    cout<< "Volume of cube C1 = "<< C1.getVolume();
}

Volume of cube C1 = 16

立方体C1的体积= 16

Similarly we can define the getter and setter functions to access private data members, inside or outside the class definition.

类似地,我们可以定义getter和setter函数来访问类定义内部或外部的私有数据成员。

翻译自: https://www.studytonight.com/cpp/member-functions-cpp.php

c ++类成员函数

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值