5

c++11中 构造函数 与 复制构造函数和赋值操作符的关系 ???

各位好,以下代码:

#include<iostream>
using namespace std;

class B {
public:
  B() {}
  virtual ~B() {}
  virtual void paly() = 0;
private:
 B(const B&) = delete;
 B& operator=(const B&) = delete;
};

class D: public B {
public: 
 explicit D(int a) {}
 void paly() {cout << "qwertyuiop" <<endl;}
};

int main() {
int a = 0;
B* bp = new D(a);

bp->paly();
delete bp;
return 0;
}

使用 g++ -Wall -std=c++11 -o main a.cc 编译没有问题;
但是注释掉B() {} 构造函数后出现错误:代码如下:

#include<iostream>
using namespace std;

class B {
public:
  ///////B() {}
  virtual ~B() {}
  virtual void paly() = 0;
private:
 B(const B&) = delete;
 B& operator=(const B&) = delete;
};

class D: public B {
public: 
 explicit D(int a) {}
 void paly() {cout << "qwertyuiop" <<endl;}
};

int main() {
int a = 0;
B* bp = new D(a);

bp->paly();
delete bp;
return 0;
}

g++报错如下:

a.cc: In constructor ‘D::D(int)’:
a.cc:16:20: error: no matching function for call to ‘B::B()’
  explicit D(int a) {}
                    ^
a.cc:10:2: note: candidate: B::B(const B&) <deleted>
  B(const B&) = delete;
  ^
a.cc:10:2: note:   candidate expects 1 argument, 0 provided

如果 把delete取消,代码如下: 又可以成功编译。

#include<iostream>
using namespace std;

class B {
public:
  ///////B() {}
  virtual ~B() {}
  virtual void paly() = 0;
private:
 ////B(const B&) = delete;
 ////B& operator=(const B&) = delete;
};

class D: public B {
public: 
 explicit D(int a) {}
 void paly() {cout << "qwertyuiop" <<endl;}
};

int main() {
int a = 0;
B* bp = new D(a);

bp->paly();
delete bp;
return 0;
}

所以我想问, 对于复制构造和赋值操作符的禁用 是会 影响 默认函数的合成吗?
c++11里面有相关的描述吗???
谢谢。

查看全部
penglijiangge
cool-warm-self-know
2019/07/08 21:09
  • c++
  • 点赞
  • 收藏
  • 回答
    私信

2个回复