介绍
本实验将引导你在 C++ 编程中实现类(Class)及其成员的概念。类是一种用户定义的数据类型,它作为对象的蓝图。类的成员可以是变量或函数,并且可以定义为 public(公有)、private(私有)或 protected(保护)。
本实验将引导你在 C++ 编程中实现类(Class)及其成员的概念。类是一种用户定义的数据类型,它作为对象的蓝图。类的成员可以是变量或函数,并且可以定义为 public(公有)、private(私有)或 protected(保护)。
首先,我们需要创建并编辑主源文件。打开终端并使用 cd
命令导航到项目目录:
cd ~/project
创建并打开主源文件:
touch main.cpp
将以下代码添加到文件中:
#include <iostream>
using namespace std;
class LabEx {
private:
int value;
public:
void input() {
cout << "Entering the input() function\n";
cout << "Enter an integer you want to display: ";
cin >> value;
cout << "Exiting the input() function\n\n";
}
void display() {
cout << "\nEntering the display() function\n";
cout << "The value entered is: " << value << endl;
cout << "Exiting the display() function\n\n";
}
};
int main() {
cout << "\n\nWelcome to LabEx :-)\n\n\n";
cout << " ===== Program to demonstrate the concept of Class, in CPP ===== \n\n";
LabEx object;
cout << "\n\nCalling the input() function from the main() method\n\n\n";
object.input();
cout << "\nCalling the display() function from the main() method\n\n\n";
object.display();
cout << "\n\nExiting the main() method\n\n\n";
return 0;
}
代码定义了一个 LabEx
类,其中包含两个成员函数 input()
和 display()
。input()
函数从用户处接收输入并将其存储在 value
中,而 display()
函数将存储的值输出到屏幕上。
在终端中运行以下命令来编译程序:
g++ main.cpp -o main && ./main
成功编译并运行后,你应该会看到以下输出:
Welcome to LabEx :-)
===== Program to demonstrate the concept of Class, in CPP =====
Calling the input() function from the main() method
Entering the input() function
Enter an integer you want to display: 5
Exiting the input() function
Calling the display() function from the main() method
Entering the display() function
The value entered is: 5
Exiting the display() function
Exiting the main() method
在本实验中,你学习了如何定义类及其成员,如何声明和初始化类的对象,以及如何使用构造函数访问类的成员。
现在,你可以利用 C++ 类和其成员的概念来编写需要用户定义数据类型的高级程序。通过应用面向对象编程(OOP)技术,这一概念还可以帮助你实现更好的代码组织和提高代码的可读性。
别忘了根据你的实现修改路径和文件名。
#include <iostream>
using namespace std;
class LabEx {
private:
int value;
public:
void input() {
cout << "Entering the input() function\n";
cout << "Enter an integer you want to display: ";
cin >> value;
cout << "Exiting the input() function\n\n";
}
void display() {
cout << "\nEntering the display() function\n";
cout << "The value entered is: " << value << endl;
cout << "Exiting the display() function\n\n";
}
};
int main() {
cout << "\n\nWelcome to LabEx :-)\n\n\n";
cout << " ===== Program to demonstrate the concept of Class, in CPP ===== \n\n";
LabEx object;
cout << "\n\nCalling the input() function from the main() method\n\n\n";
object.input();
cout << "\nCalling the display() function from the main() method\n\n\n";
object.display();
cout << "\n\nExiting the main() method\n\n\n";
return 0;
}