常函數和常對象的應用
阿新 • • 發佈:2017-08-18
ace 對象 names void err 函數 ret ons span
#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(intnum1) 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(); }
常函數和常對象的應用