【学习笔记】C/C++

1. C语言中的 scanf() 函数


该函数包含在头文件 <stdio.h> 或者 <cstdio> (在C++中使用时)

函数的返回值指的是

所输入的数据与格式字符串匹配的次数。

意思就是该函数返回已成功赋值的数据项数,出错时返回 EOF (End_of_File,是一个预定义常量,表示文件末尾,值为-1)

简单示例:

 1 #include <stdio.h>
 2 
 3 int main(void)
 4 {
 5     int a, b;
 6     int input = scanf("%d %d", &a, &b);
 7     printf("input = %d\n", input);
 8     
 9     return 0;
10 }

此时输入 1 2 

得到输出 input = 2 

上述结果表示正确匹配,若出现错误,如输入 1 a 

第二个值匹配失败,整型变量b无法得到字符‘a’,依旧是一个未赋值前不确定的值,则此时输出结果为 input = 1 

总之,我们可通过函数scanf( )返回值,来检测输入格式的正确性。

2. C++类与对象

2.1 问题:我们需要将一个类的所有实例都保存在一个容器中,同时又不需要类的使用者进行其他的操作,该如何实现?

方法:在类中定义一个static类型的容器作为类的成员变量,构造对象时将对象的地址添加到容器中,析构时再将其从容器中删除。

 1 #include <iostream>
 2 #include <list>
 3 #include <algorithm>
 4 
 5 using namespace std;
 6 
 7 class MyClass {
 8 protected:
 9    int value_;
10 public:
11    static list<MyClass*> instances_;
12    MyClass(int val);
13   ~MyClass();
14    static void showList();
15 };
16 
17 list<MyClass*> MyClass::instances_;
18 
19 MyClass::MyClass(int val) {
20    instances_.push_back(this);
21    value_ = val;
22 }
23 
24 MyClass::~MyClass() {
25    list<MyClass*>::iterator p =
26       find(instances_.begin(), instances_.end(), this);
27    if (p != instances_.end())
28       instances_.erase(p);
29 }
30 
31 void MyClass::showList() {
32    for (list<MyClass*>::iterator p = instances_.begin();
33         p != instances_.end(); ++p)
34       cout << (*p)->value_ << endl;
35 }
36 
37 int main(int argc, char **argv) {
38    MyClass a(1);
39    MyClass b(10);
40    MyClass c(100);
41    MyClass::showList();    // 输出的结果为1,10,100
42    return 0;  
43 }

未完待续...

猜你喜欢

转载自www.cnblogs.com/phillee/p/10647808.html