C++构造函数使用的多种方法
2023-09-11 14:15:08 时间
// classes and uniform initialization
#include <iostream>
using namespace std;
class Circle {
double radius;
public:
Circle(double r) { radius = r; }
double circum() {return 2*radius*3.14159265;}
};
int main () {
Circle foo (10.0); // functional form
Circle bar = 20.0; // assignment init.
Circle baz {30.0}; // uniform init.
Circle qux = {40.0}; // POD-like
cout << "foo's circumference: " << foo.circum() << '\n';
cout << "bar circumference: " << bar.circum() << '\n';
cout << "bazcircumference: " << baz.circum() << '\n';
cout << "qux circumference: " << qux.circum() << '\n';
return 0;
}
Rectangle rectb; // default constructor called
Rectangle rectc(); // function declaration (default constructor NOT called)
Rectangle rectd{}; // default constructor called
Member initialization in constructors
When a constructor is used to initialize other members, these other members can be initialized directly, without resorting to statements in its body. This is done by inserting, before the constructor's body, a colon (:) and a list of initializations for class members. For example, consider a class with the following declaration:
class Rectangle {
int width,height;
public:
Rectangle(int,int);
int area() {return width*height;}
};
The constructor for this class could be defined, as usual, as:
Rectangle::Rectangle (int x, int y) { width=x; height=y; }
But it could also be defined using member initialization as:
Rectangle::Rectangle (int x, int y) : width(x) { height=y; }
Or even:
Rectangle::Rectangle (int x, int y) : width(x), height(y) { }
Note how in this last case, the constructor does nothing else than initialize its members, hence it has an empty function body.
相关文章
- C 和 C++字符串详解
- C++之萃取技术(traits)
- qt实现web服务器加载vue应用进行C++和html混合编程-连载【6】-企业级系统开发实战连载系列 -技术栈(vue、element-ui、qt、c++、sqlite)
- 【解决】缺少libstdc++.so.6库的原因及解决的方法
- 用形态学的方法实现图像的角点检测的算法原理详解和代码实现(Pyton和C++代码)
- 利用C++的std::vector定义OpenCV的MAT数组的方法
- 用形态学的方法实现图像的角点检测(附Pyton和C++代码)
- 将C/C++程序的变量数据导入到MATLAB中的方法
- 46 C++ - 非自动继承的函数
- 90 C++ - 常用拷贝和替换算法
- C++程序设计:原理与实践(进阶篇)15.1 存储和处理数据
- c#,c++,qt中多线程访问UI控件线程的问题汇总
- c++中LPCTSTR,LPTSTR 解释
- C++中常见的字符判断与处理方法
- 《C++游戏编程入门(第4版)》——2.11 理解游戏主循环
- 《C++编程惯用法——高级程序员常用方法和技巧》——1.4 使用CRC卡片来辅助设计
- 《C++编程惯用法——高级程序员常用方法和技巧》——1.6 问题
- 《C++编程惯用法——高级程序员常用方法和技巧》——第2章 类
- [第七届蓝桥杯省赛C++B组]煤球数目
- 理清gcc、libc、libstdc++的关系(libstdc++是gcc搞的,libc++是llvm搞的,他们都是C++标准库的实现)
- QT跟VC++结合来进行插件的验证机制(遍历vtable,保证虚函数的个数一致,也可使用Q_INVOKABLE宏定义)
- 【C/C++内存分布】
- c++ atna2 特殊值处理
- 181、【动态规划】leetcode ——72. 编辑距离(C++版本)
- 44、【树和二叉树】Trie(前缀树/搜索树)字符串统计(C/C++版)
- C++ 基础入门 之 注释 ( // 和 /**/ )/变量 /常量 ( #define 和 const )/关键字/标识符(变量名)命名规则
- VC++6.0环境下调试c语言代码的方法和步骤_附图
- 编程语言拟人化:Java、C++、Python、Ruby、PHP、C#、JS!--隆重推荐转
- C++字符串切割的两种方法
- C/C++ 遍历文件夹(最全方法)
- C/C++文件读写(最全方法,多种实现)
- C/C++宽窄字符转换与输出(多种方法)
- C++实操 - 函数无参数的表示方法
- Stuck in the process of compiling C++ extensions 卡住解决方法 time.sleep(self.wait_seconds)