#include <iostream> #include <string> using namespace std; class student { private: string name; int age; public: student(){} student(string name,int age) { this->name = name; this->age = age; } string getName() { return this->name; } int getAge() { return this->age; } #if 1 void showStudent()const //常函数,常函数重载 { // this->name = "zhangsan";//error,常函数中不允许修改类的数据成员的值 cout << "void showStudent()const" << endl; cout << this->name << " " << this->age <<endl; } #endif #if 0 void showStudent() //一般函数 { this->name = "zhangsan"; //一般函数中允许修改变量的值 cout << "void showStudent()" <<endl; cout << this->name << " " << this->age <<endl; } #endif }; #if 0 int showint(int num1) const //error:常函数只能存在于类中 { cout << num1 << endl; } #endif int main() { student stu("zhangsan",22); //一般对象,可以调用非常函数,也可以调用常函数 stu.showStudent(); const student stu2("lisi",33); //常对象,不能修改对象的值 const int i = 10; stu2.showStudent(); }
时间: 2024-10-07 07:53:43