简单c++代码
cpp#include <iostream>
int main() {
int num1, num2, sum;
// 提示用户输入第一个整数
std::cout << "Enter the first number: ";
std::cin >> num1;
// 提示用户输入第二个整数
std::cout << "Enter the second number: ";
std::cin >> num2;
// 计算两个整数的和
sum = num1 + num2;
// 显示结果
std::cout << "The sum of " << num1 << " and " << num2 << " is: " << sum << std::endl;
return 0;
}
这个程序首先提示用户输入两个整数,然后计算它们的和,并将结果显示出来。
cpp#include <iostream>
#include <string>
// 定义学生类
class Student {
private:
std::string name;
int age;
public:
// 构造函数
Student(std::string studentName, int studentAge) {
name = studentName;
age = studentAge;
}
// 设置学生姓名
void setName(std::string studentName) {
name = studentName;
}
// 获取学生姓名
std::string getName() {
return name;
}
// 设置学生年龄
void setAge(int studentAge) {
age = studentAge;
}
// 获取学生年龄
int getAge() {
return age;
}
};
int main() {
// 创建学生对象
Student student1("Alice", 20);
// 获取学生信息并显示
std::cout << "Student Name: " << student1.getName() << std::endl;
std::cout << "Student Age: " << student1.getAge() << std::endl;
// 修改学生信息
student1.setName("Bob");
student1.setAge(22);
// 再次获取并显示学生信息
std::cout << "\nUpdated Student Name: " << student1.getName() << std::endl;
std::cout << "Updated Student Age: " << student1.getAge() << std::endl;
return 0;
}
这个程序定义了一个 Student 类,其中包含了学生的姓名和年龄。在 main 函数中,它创建了一个 Student 对象并初始化其姓名和年龄。然后,它使用类的方法来获取和设置学生的姓名和年龄,并将结果显示在控制台上。