浙大 C++
- 查询 g++ 使用的版本
g++ -dM -E -x c++ /dev/null | grep -F __cplusplus
C++标准 __cplusplus值
C++ 11 201103L
C++ 14 201402L
C++ 17 201703L
- 指定 c++ 版本进行编译
g++ -std=c++17 main.cpp
可以指定的值:
c++98
c++11
c++14
c++17
c++20
- 使用 gcc 编译 c++ 代码
gcc main.cpp -lstdc++
与 g++ main.cpp 是同样的效果
- 打印出gcc提供的警告信息
g++ -Wall main.cpp
向上造型
多态性
#include <iostream>
using namespace std;
class Point
{
// int x, y;
// public:
// Point(){};
// Point(int x, int y) : x(x), y(y){};
};
class Shape
{
public:
Shape(){};
virtual ~Shape(){};
virtual void render();
void move(const Point &);
// virtual void resize();
protected:
Point center;
};
void Shape::render()
{
}
void Shape::move(const Point &p)
{
}
class Ellipse : public Shape
{
public:
Ellipse(float max, float min) : max(max), min(min){};
virtual void render();
protected:
float max, min;
};
void Ellipse::render()
{
cout << "max:" << max << " & min:" << min << endl;
}
class Circle : public Ellipse
{
public:
Circle(float radios) : Ellipse(radios, radios) {}
virtual void render();
};
void Circle::render()
{
cout << "radios:" << max << endl;
}
void render(Shape *p)
{
p->render();
}
int main()
{
Ellipse e1(1.0, 2.0);
Circle c1(3.0);
render(&e1);
render(&c1);
cout << "" << endl;
}
多态性的实现
class A
{
public:
A():i(100){};
virtual void f(){cout << i << endl;};
private:
int i;
};
int main()
{
A a;
a.f();
cout << "sizeof(A)=" << sizeof(a) << endl;
cout << "sizeof(int)=" << sizeof(int) << endl;
int *p = (int*)&a;
p++;
p++;
cout << *p << endl;
}
使用 vtable 表实现