我们在 C++ 类的内部定义的 变量 被称为成员变量,C++ 类静态成员变量是所有类的对象所共有的,但普通的非静态成员变量是每个对象实例私有的数据。
class ClassName
{
public:
Type paramter;
};
参数 | 描述 |
---|---|
Type | 成员类型名。 |
paramter | 成员变量名。 |
我们在类 ClassName 中,定义了一个成员 paramter,其类型为 Type。
类的成员变量可以定义 0 到多个。
成员变量的访问只能使用对象访问。
instance.paramter;
参数 | 描述 |
---|---|
instance | 类的对象。 |
paramter | 成员变量名。 |
我们访问了类实例 instance 里面的成员变量 paramter。
通过对象访问成员变量
#include <iostream>
using namespace std;
class Student
{
public:
Student()
{
}
string name;
};
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
Student stu;
stu.name = "HaiCoder";
Student stu1;
stu1.name = "Jobs";
cout << "stu name = " << stu.name << ", stu1 name = " << stu1.name << endl;
return 0;
}
程序运行后,控制台输出如下:
我们创建了一个类 Student,接着,为该类添加了一个成员变量 name,接着,我们创建了一个 Student 类的实例,并通过实例来调用成员变量,我们可以看到,我们为两个不同的对象设置了成员变量的值。
最后,他们的值各不相同,因为,成员变量是对象私有的。
通过实例访问实例属性
#include <iostream>
using namespace std;
class Student
{
public:
Student(string name, int age)
{
sname = name;
sage = age;
}
void sayHi()
{
cout << "I am " << sname << ", I am " << sage << " years old" << endl;
}
string sname;
int sage;
};
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
Student stu("HaiCoder", 109);
stu.sayHi();
Student stu1("Jobs", 52);
stu1.sayHi();
return 0;
}
程序运行后,控制台输出如下:
我们创建了一个类 Student,接着,为该类添加了一个两个成员变量,即 sname 和 sage,接着,我们在构造方法里面,将构造函数的参数 name 和 age 分别赋值给类 Student 的成员变量 sname 和 sage。
最后,我们在函数 sayHi 里面访问了成员变量,并输出了它们的值。
我们在 C++ 类的内部定义的变量被称为成员变量,C++ 类的静态成员变量是所有类的对象所共有的,但普通的非静态成员变量是每个对象实例私有的数据。