将下列代码改成类外定义class Contact { public: Contact(string name, string phone, string qq, string email, string birthplace) : name(name), phone(phone), qq(qq), email(email), birthplace(birthplace) {} string getName() const { return name; } string getPhone() const { return phone; } string getQQ() const { return qq; } string getEmail() const { return email; } string getBirthplace() const { return birthplace; } private: string name; string phone; string qq; string email; string birthplace; };
时间: 2024-01-16 19:01:50 浏览: 23
在类外面定义 Contact 类的成员函数的语法如下:
```cpp
返回类型 类名::成员函数名(参数列表) {
// 函数体
}
```
将 Contact 类的成员函数改为类外定义的方式如下:
```cpp
class Contact {
public:
Contact(string name, string phone, string qq, string email, string birthplace);
string getName() const;
string getPhone() const;
string getQQ() const;
string getEmail() const;
string getBirthplace() const;
private:
string name;
string phone;
string qq;
string email;
string birthplace;
};
Contact::Contact(string name, string phone, string qq, string email, string birthplace)
: name(name), phone(phone), qq(qq), email(email), birthplace(birthplace)
{
}
string Contact::getName() const {
return name;
}
string Contact::getPhone() const {
return phone;
}
string Contact::getQQ() const {
return qq;
}
string Contact::getEmail() const {
return email;
}
string Contact::getBirthplace() const {
return birthplace;
}
```
其中,构造函数和每个成员函数都在类外进行了定义。注意,在定义成员函数时需要在函数名前加上类名和作用域解析运算符 `::`。成员函数的实现与类内定义是一样的,只不过需要在声明时加上类名和函数名,以及在定义时加上作用域解析运算符。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)