C++ 类的普通成员方法是定义在 类 内部的方法,C++ 的成员方法与普通 函数 一样,可以有任何的参数和返回值,同时,也支持 默认参数 和 函数重载。
class ClassName
{
public:
Type funcName(paramterType paramter)
{
}
};
参数 | 描述 |
---|---|
Type | 成员方法的返回值类型。 |
funcName | 成员方法名。 |
paramterType | 成员方法参数类型。 |
paramter | 成员方法形参。 |
我们在 ClassName 类里面,定义了一个成员方法 funcName。
C++ 的成员方法只能通过通过 “对象.方法名” 的方法来调用。
instance.funcName(params)
参数 | 描述 |
---|---|
instance | 类的对象。 |
funcName | 成员方法。 |
params | 参数。 |
通过 “实例.方法名” 的方法,调用成员方法。
通过对象访问类成员方法
#include <iostream>
using namespace std;
class Student
{
public:
Student()
{
}
void sayHello()
{
cout << "Hello, I am student" << endl;
}
};
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
Student stu;
stu.sayHello();
return 0;
}
程序运行后,控制台输出如下:
我们使用 “对象.类成员方法” 的形式调用类成员方法。
类成员方法可以支持重载
#include <iostream>
using namespace std;
class Student
{
public:
Student()
{
}
void sayHello()
{
cout << "Hello, I am student" << endl;
}
void sayHello(string name)
{
cout << "Hello, i am " << name << endl;
}
};
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
Student stu;
stu.sayHello();
stu.sayHello("Jobs");
return 0;
}
程序运行后,控制台输出如下:
我们重载了类的成员方法 sayHello。
类成员方法可以支持默认参数
#include <iostream>
using namespace std;
class Student
{
public:
Student()
{
}
void sayHello(string name = "Jobs")
{
cout << "Hello, I am student,You can call me " << name << endl;
}
};
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
Student stu;
stu.sayHello();
stu.sayHello("Gates");
return 0;
}
程序运行后,控制台输出如下:
我们给成员方法 sayHello 设置了默认参数。
C++ 类的普通成员方法是定义在类内部的方法,C++ 的成员方法与普通函数一样,可以有任何的参数和返回值,同时,也支持默认参数和函数重载。