【C++】工作中遇到的难点

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/w417950004/article/details/78782114

一,explicit
C++ explicit关键字用来修饰类的构造函数,表明该构造函数是显式的。
构造函数有显示和隐式之分。构造函数默认的式隐式的,如下:

1. class MyClass  
2. {  
3. public:  
4. MyClass( int num );  
5. }  
6. //.  
7. MyClass obj = 10; //ok,convert int to MyClass 

在上面的代码中编译器自动将整型转换为MyClass类对象,实际上等同于下面的操作:

1. MyClass temp(10);  
2. MyClass obj = temp; 

这样就进行了隐式转换。若是不想对象被这样赋值就需要使用explicit关键字。在声明构造函数的时候前面添加上explicit即可,这样就可以防止这种自动的转换操作。如下所示:

1. class MyClass  
2. {  
3. public:  
4. explicit MyClass( int num );  
5. }  
6. //.  
7. MyClass obj = 10; //err,can't non-explict convert 

再赋值时会报错。

二,provide?

cin.ignore(256,’\n’)
表示对于输入的数来说,会忽略”\n”之前的数,但是忽略的最大长度为256个字符。

三,技巧

while (true) {
    cout << "Enter a phone number (or leave blank to finish): ";
    string number;
    getline(cin, number);
    if (number.empty()) {
      break;
    }
}
for (int j = 0; j < person.phones_size(); j++) {
      const tutorial::Person::PhoneNumber& phone_number = person.phones(j);
      switch (phone_number.type()) {
        case tutorial::Person::MOBILE:
          cout << "  Mobile phone #: ";
          break;
        case tutorial::Person::HOME:
          cout << "  Home phone #: ";
          break;
        case tutorial::Person::WORK:
          cout << "  Work phone #: ";
          break;
      }

      cout << phone_number.number() << endl;
  }

四,cerr ?

cerr << "Usage:  " << argv[0] << " ADDRESS_BOOK_FILE" << endl;

五,fstream

fstream output("./log", ios::out | ios::trunc | ios::binary);  

猜你喜欢

转载自blog.csdn.net/w417950004/article/details/78782114