用C++写一个mytel和telmanager类,后者有mytel的子对象,实现查找,增添,删除,修改
时间: 2023-11-27 20:03:24 浏览: 36
js代码-myTel
好的,下面是一个实现增删改查的MyTel和TelManager类的C++代码:
```cpp
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class MyTel {
public:
MyTel(string name, string number) : name_(name), number_(number) {}
string getName() const { return name_; }
string getNumber() const { return number_; }
void setName(string name) { name_ = name; }
void setNumber(string number) { number_ = number; }
private:
string name_;
string number_;
};
class TelManager {
public:
void addMyTel(MyTel mytel) { mytels_.push_back(mytel); }
void printAllMyTels() const {
for (const auto& mytel : mytels_) {
cout << "Name: " << mytel.getName() << ", Number: " << mytel.getNumber() << endl;
}
}
MyTel* findMyTel(string name) {
for (auto& mytel : mytels_) {
if (mytel.getName() == name) {
return &mytel;
}
}
return nullptr;
}
void deleteMyTel(string name) {
for (auto it = mytels_.begin(); it != mytels_.end(); ++it) {
if (it->getName() == name) {
mytels_.erase(it);
break;
}
}
}
void modifyMyTel(string name, string new_name, string new_number) {
for (auto& mytel : mytels_) {
if (mytel.getName() == name) {
mytel.setName(new_name);
mytel.setNumber(new_number);
break;
}
}
}
private:
vector<MyTel> mytels_;
};
int main() {
MyTel mytel1("Alice", "1234567");
MyTel mytel2("Bob", "2345678");
TelManager telmanager;
telmanager.addMyTel(mytel1);
telmanager.addMyTel(mytel2);
// 查找
cout << "Find \"Alice\"" << endl;
MyTel* mytel = telmanager.findMyTel("Alice");
if (mytel) {
cout << "Found: Name: " << mytel->getName() << ", Number: " << mytel->getNumber() << endl;
} else {
cout << "Not found" << endl;
}
// 增加
cout << endl << "Add \"Carl\", \"3456789\"" << endl;
telmanager.addMyTel(MyTel("Carl", "3456789"));
telmanager.printAllMyTels();
// 删除
cout << endl << "Delete \"Alice\"" << endl;
telmanager.deleteMyTel("Alice");
telmanager.printAllMyTels();
// 修改
cout << endl << "Modify \"Bob\"" << endl;
telmanager.modifyMyTel("Bob", "Bobby", "4567890");
telmanager.printAllMyTels();
return 0;
}
```
这里我们在MyTel类中添加了setName和setNumber方法,用于修改MyTel对象的名字和电话号码。在TelManager类中,我们添加了findMyTel、deleteMyTel和modifyMyTel方法,用于查找、删除和修改MyTel对象。在main函数中,我们演示了如何使用这些方法来增删改查MyTel对象。
阅读全文