定义一个Person类常对象,并通过此对象访问 display(), change_addr等函数
时间: 2024-02-20 10:01:14 浏览: 60
好的,这是一个示例代码:
```cpp
#include <iostream>
using namespace std;
class Person {
private:
const string name;
const int age;
string address;
public:
Person(const string& nm, int a, const string& addr) : name(nm), age(a), address(addr) {}
void display() const {
cout << name << " is " << age << " years old and lives at " << address << endl;
}
void change_addr(const string& new_addr) {
address = new_addr;
}
};
int main() {
const Person p("Tom", 25, "123 Main St.");
p.display(); // 调用常对象的成员函数 display
p.change_addr("456 Elm St."); // 调用常对象的成员函数 change_addr
p.display(); // 再次调用常对象的成员函数 display,检查地址是否已更改
return 0;
}
```
运行结果:
```
Tom is 25 years old and lives at 123 Main St.
Tom is 25 years old and lives at 456 Elm St.
```
阅读全文