类
class与struct
为什么c++里面经常定义struct?
利用struct默认访问修饰符为public的特性,
属性
static成员
#include<iostream>
using std::cout;
using std::endl;
class A {
public:
static long a;
A() {
}
};
long A::a = 233; //不初始化会报错
int main() {
A aa;
aa.a = 1;
cout << aa.a << '\n';
A bb;
bb.a = 2;
cout << aa.a << '\n';
}
继承
虚拟继承
在未加virtual时会出现这种情况
代码中需要指定调用哪个父类的方法,这样就很奇怪
而加了virtual后就不需要了
#include<iostream>
using std::cout;
using std::endl;
class Base {
protected:
int value;
public:
Base() {
cout << "in Base" << endl;
}
};
class DerivedA : virtual protected Base {
public:
DerivedA() {
cout << "in DerivedA" << endl;
}
};
class DerivedB : virtual protected Base {
public:
DerivedB() {
cout << "in DerivedB" << endl;
}
};
class MyClass : DerivedA, DerivedB {
public:
MyClass() {
cout << "in MyClass" << value << endl;
}
};
int main() {
MyClass myClass;
}
拷贝构造函数
就是一个构造函数,完了参数是同类型的对象,在使用等号赋值的时候会调用拷贝构造函数
#include<iostream>
using std::cout;
using std::endl;
struct A {
public:
int a;
A(int _a) {
a = _a;
}
A(const A &obj) {
cout << "调用拷贝构造函数" << '\n';
a = obj.a + 1;
}
};
int main() {
A a1(233);
A a2 = a1; //调用拷贝构造函数
cout << a2.a;
}
技巧:禁止类copy
干掉copy 构造函数即可
class DBImpl : public DB {
public:
DBImpl(const DBOptions& options, const std::string& dbname,
const bool seq_per_batch = false, const bool batch_per_txn = true,
bool read_only = false);
// No copying allowed
DBImpl(const DBImpl&) = delete;
void operator=(const DBImpl&) = delete;
标签:std,const,cout,C++,public,using,Class,DBImpl
From: https://www.cnblogs.com/attack204/p/16823718.html