优化employee em("员工", "john"); std::cout << em << std::endl;
时间: 2023-11-30 20:02:37 浏览: 42
可以使用C++11的右移运算符重载来简化输出语句,将其写成一个友元函数,代码如下:
```c++
#include <iostream>
#include <string>
class employee {
public:
employee(std::string job, std::string name) : job_(job), name_(name) {}
friend std::ostream& operator<<(std::ostream& os, const employee& e) {
os << e.job_ << ": " << e.name_;
return os;
}
private:
std::string job_;
std::string name_;
};
int main() {
employee em("员工", "john");
std::cout << em << std::endl;
return 0;
}
```
输出结果:
```
员工: john
```
相关问题
std::cout << << std::endl
这段代码使用了C++的标准输出流std::cout,将字符串"Hello world!!!"输出到控制台,并在末尾添加了一个换行符std::endl。其中<<是输出运算符,用于将字符串插入到输出流中。如果使用了using namespace std,则可以省略std::,直接使用cout和endl输出。以下是两种写法的示例代码:
使用std::cout输出:
```cpp
#include <iostream>
int main() {
std::cout << "Hello world!!!" << std::endl;
return 0;
}
```
使用using namespace std输出:
```cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello world!!!" << endl;
return 0;
}
```
std::cout << std:: endl;
std::cout << std::endl; 是C++中用于输出换行的语句。它将换行符输出到标准输出流(std::cout)中。 这样可以使输出结果在控制台中换行显示。<span class="em">1</span><span class="em">2</span><span class="em">3</span><span class="em">4</span>
相关推荐
![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)