C++中几个问题

来源:互联网 发布:php开源websocket 编辑:程序博客网 时间:2024/06/16 10:45

C++中,关键字const在函数前/后使用分别的意义

以下代码:用链表实现stack

// Stack类中:template <class T>const T Stack<T>::Top() const {    if (top == nullptr || count == 0) {        cout << "There have no data, can't top." << endl;        return 0;    }    return top->data;}// main函数中:Stack<int> s;s.Push(1);int t = s.Top();cout << t << endl; // output: 1

关键字const在函数之前

返回值:const int 对象

int &t = s.Top(); // error

关键字const在函数之后

这是说 函数Func是一个const成员函数,const成员函数不能修改成员变量(除非声明为mutable的变量):

在class Stack中有一个成员变量:count;

如果在函数Top)_中,你要:this->count = 1; // compiler error

// Top()函数体中this->count = 1; // error

关键字const在变量前后不同位置,含义不同

  • first:

    const int *Constant1;

    int const *Constant1;

    Constant1 是指针类型,指向constant int类型。

  • second

    int * const Constant2;

    这是一个constant指针,指向一个integer

  • third

    int const * const Constant3;

    Constant3是一个constant指针指向constant int类型数据。

可以试下它:

#include <iostream>using namespace std;int main(void) {    // first    const int *p = nullptr; //int const *p = nullpte;    int a = 0;    const int b = 1;    p = &a;//    *p = 2;    cout << *p << endl;    p = &b;//    *p = 1;    cout << *p << endl;    // second    a = 0;    int * const q = &a;//    b = 1; // error, it's a const integer    int c = 2;//    q = &c; // error, pointer q is constant    cout << *q << endl;       return 0;}

C中检查输入是否是numeric

for (int i = 0; str[i] != '\0'; i++) {    if (!isdifit(str[i]))        return false;}return true;

malloc VS new

C: malloc; free

C++: new; delete

一句话:如果不是被用C,那就不要去用malloc

NULL vs nullptr

  • nullptr 总是指针类型
  • C的NULL直接带到C++中了,其中,cout << NULL << endl; // 0

在建立一个指针时,要立马给它初始化,若指向为空,则:

int *p = nullptr;

void类型函数是否可以用return返回

可以

return void(); // return;

gcc 参数 -Wall

gcc -Wall [options] [source files] [object files] [-o output file]

gcc -Wall -o test test.c

区别在于可以更为详细详细地输出信息,可以试一下:

// test.c#include <stdio.h>int main(void) {    printf("Hello World!\n");    int i = 0;}

文件重定向

当反复从键盘敲入测试用例时,繁琐,可以用文件重定向

// hello.cpp#include <iostream>using namespace std;int main(void) {    int a, b;    cin >> a >> b;    cout << a << ", " << b << endl;    return 0;}
$ g++ -o hello hello.cpp$ ./hello < helloIn.txt > helloOut.txt
0 0
原创粉丝点击