- 如果一个类接受参数只有string的构造函数和参数只有istream&的构造函数都使用默认参数,会产生二义性。
class MyClass { public: MyClass(const string& str = "default") { // 构造函数实现 } MyClass(istream& is = cin) { // 构造函数实现 } };
- 委托构造函数使用它所属类的其他构造函数执行它自己的初始化过程,即把它自己的一些职责委托给了其他构造函数。注,如果使用了委托构造函数,则初始化列表不能含有其他列表初始化表达式,或者基类的构造函数。
#include <iostream> #include <climits> #include <vector> #include <iterator> #include <string> #include <initializer_list> #include <cassert> #include <algorithm> typedef std::string Type; class Base { public: int d = 0; Base(int num) :d(num) {}; Base() = default; }; class MyClass :public Base { public: int a = 0; std::string b; double c = 0; MyClass(int num, std::string str) :a(num), b(str) { }; MyClass(int a, std::string b, double c) :MyClass(a, b)/*, Base(c),c(c)*/ {}; //被注释掉的部分是不允许使用的 }; int main() { MyClass base(1, "Std", 9.2); std::cout << base.a << " " << base.b << " " << base.c << std::endl; }
- 聚合类是所有成员都是public的,没有定义任何构造函数,没有类内初始值,没有基类和virtual函数的类
class Data { public: int a; void Func(int b) { std::cout<<a*b<<std::endl; } }
- 字面值常量类型可以是字面值类型的聚合类,也可以是满足一下要求的类:
- 数据成员都必须是字面值类型。
- 类必须至少含有一个constexpr构造函数。
- 如果一个数据成员含有类内初始值,则内置类型成员的初始值必须是一条常量表达式;或者如果成员属于某个类类型,则初始化必须使用成员自己的constrexpr。
- 类必须使用析构函数的默认定义,该成员负责销毁类的对象。
class Vector3 { public: int x; int y; int z; void Func() { std::cout << x + y + z << std::endl; } }; class VecChird { int z; public: explicit constexpr VecChird(int a) :z(a) {}; }; class Vector2 { private: int x = 2; int y; VecChird vec; public: constexpr Vector2(int a = 0, int b = 0, int v = 0) :x(a), y(b), vec(v) {}; constexpr bool isWhat() { return x * y == 0; } };
- 静态数据成员不属于类的任何一个对象,所以他们不是由类的构造函数初始化的。一般来说,不能在类的内部初始化静态成员,只能在类的外部定义和初始化每个静态成员。如果需要初始化静态常变量成员,可以使用constexpr修饰,而不是const(const只能初始化整形)。静态成员函数不能对this指向的数据进行操作。
#include <iostream> #include <climits> #include <vector> #include <fstream> #include <iterator> #include <string> #include <initializer_list> #include <cassert> #include <algorithm> class Account { public: static double rate(){} static void rate(double); static double val; static constexpr double num = 10.0; private: Account() { amount = 0; val = 0; } std::string owner; double amount; static double interestRate; void Func() { ++val; } static double initRate() { return 2; } ~Account() { ++val; } }; void Account::rate(double newRate) { interestRate = newRate; } double Account::interestRate = initRate(); int main() { }
- 静态数据成员可以是不完全类型,即声明和定义分开,非静态数据成员不可以是不完全类型,但是非静态引用/指针成员可以是完全类型,静态数据成员可以作为类中的函数默认实参。而非静态成员不能作为函数默认实参。
class Account { public: friend void Func(Account acc = Account::mem1) //如果使用友元传mem1默认参数,需要加上Account::即所在类 { ; } static const Account mem1; Account* mem2; Account& mem3; //Account mem4 数据成员必须是完全类型,即声明和定义要一起 private: };
cpp primer笔记040-函数与类
于 2023-10-06 15:26:01 首次发布