C++刷题笔记

  1. 初始化string数组

    string numbers[12] = {{"1"},{"2"},{"10"},{"11"},{"23"},{"25"},{"31"},{"36"},{"37"},{"102"},{"325"},{"438"}};
    
  2. 填充

for(int i = 0;i < 12;i++){
    cout << setw(6) << i + 1;
    while(s[i].num.size() < 3){
        s[i].num = "0" + s[i].num;
    }
    cout << setw(6) << s[i].num;
    cout << setw(6) << s[i].grade;
    cout << endl;
}
  1. 使用类模版在类前加template,示例化时classname a;

  2. 传实例时候记得传引用

  3. 如果定义了友元函数,那么这个函数函数可以访问类的私有成员

  4. 注意数据类型不要定义错了,特别是临时变量和类内的数据类型要一致

Clock operator++(Clock& op){
op.Second++;
if(op.Second >= 60){
op.Second -= 60;
op.Minute += 1;
if(op.Minute >= 60){
op.Minute -= 60;
op.Hour ++;
op.Hour %= 24;
}
}
return op;
}
Clock operator++(Clock& op,int){
Clock c = op;
++(op);
return c;
}

注意前置运算符重载没有参数,后置运算符重载有参数,前置运算符重载返回的为处理后的对象,后置运算符重载先用一个临时变量来存储改变之前的对象,然后对原对象进行改变,返回的是处理之前的对象
8. ```c++
class Student{
public:
    Student(){
        score = 0;
        isPass = 0;
        name = "";
    };
    friend istream& operator>> (istream& input,Student& s){
        input >> s.name >> s.score;
        cnt++;
        if(s.score >= 60){
            s.isPass = 1;
        }else{
            s.isPass = 0;
        }
        return input;
    }
    friend ostream& operator<<(ostream& output,Student& s){
        output << cnt << ". " << s.name << " ";
        if(s.isPass == 1){
            output << "PASS";
        }else{
            output << "FAIL";
        }
        return output;
    }
    static int cnt;
private:
    string name;
    int score;
    int isPass;
};
int Student::cnt = 0;

今天又一次在传引用的时候出错了,在重载流提取>>和流插入<<时候要出传入的变量为类对象的引用,而而且还有一个小问题,就是在最后要返回istream引用input和ostream引用output,这样才能进行连续的输入输出
8. 控制输出个数setprecision(n),n即为输出个数,若要精确到小数点后几位,则在上式后面加上fixed;

posted @ 2023-02-28 20:30  Travelever  阅读(18)  评论(0)    收藏  举报