复制构造函数和赋值操作符
Copy constructor and assignment operator
下面是一段代码:
class GameBoard
{
public:
GameBoard() { cout<<"Gameboard()n"; }
GameBoard(const GameBoard&)
{
cout<<"GameBoard(const GameBoard&)n";
}
GameBoard& operator=(const GameBoard&)
{
cout<<"GameBoard& operator=(const GameBoard&)n";
return *this;
}
~GameBoard() { cout<<"~GameBoard()n";};
};
class Game
{
GameBoard gb;
public:
Game(){ cout<<"Game()n"; }
Game(const Game&g):gb(g.gb)
{
cout<<"Game(const Game&g)n";
}
Game(int) {cout<<"Game(int)n"; }
Game& operator=(const Game& g)
{
gb=g.gb;
cout<<"Game::operator=()n";
return *this;
}
class Other
{
public:
Other(){cout<<"Game::Other()n";}
};
operator Other() const
{
cout<<"Game::Operator Other()n";
return Other();
}
~Game() {cout<<"~Game()n";}
};
class Chess: public Game {};
void f(Game::Other) {}
class Checkers : public Game
{
public:
Checkers() {cout<<"Checkers()n";}
Checkers(const Checkers& c) : Game(c)
{
cout<<"Checkers(const Checkers& c)n";
}
Checkers operator=(const Checkers& c)
{
Game::operator=(c);
cout<<"Checkers operator=(const Checkers& c)n";
return *this;
}
};
int main()
{
Chess d1;
Chess d2(d1);
d1=d2;
f(d1);
Game::Other go;
Checkers c1,c2(c1);
c1=c2;
}
下面是输出
Gameboard() //Constructing d1
Game()
GameBoard(const GameBoard&)
Game(const Game&g) //d2(d1)
GameBoard& operator=(const GameBoard&)
Game::operator=() //d1=d2
Game::Operator Other() //f(d1)
Game::Other()
Game::Other() //go
Gameboard() //c1
Game()
Checkers()
GameBoard(const GameBoard&) //c2(c1)
Game(const Game&g)
Checkers(const Checkers& c)
GameBoard& operator=(const GameBoard&) //c1=c2
Game::operator=()
Checkers operator=(const Checkers& c)
GameBoard(const GameBoard&) ?
Game(const Game&g) ?
Checkers(const Checkers& c) ?
~Game()
~GameBoard()
~Game()
~GameBoard()
~Game()
~GameBoard()
~Game()
~GameBoard()
~Game()
~GameBoard()
我的问题是为什么最后一组复制构造函数被调用?
因为您的Checkers
赋值操作符返回一个值而不是一个引用,因为它是习惯的。
Checkers operator=(const Checkers& c)
应该Checkers& operator=(const Checkers& c)
相关文章:
- C++ 基本 CTOR 说明 - 为什么不调用赋值/复制构造函数
- 错误的数组初始化与赋值副本构造函数初始化
- 赋值复制构造函数
- 复制构造函数,赋值操作符重载
- 通过调用Move赋值操作符实现Move构造函数
- 单参数构造函数和赋值操作符
- 如何从复制赋值操作符调用复制构造函数
- c++复制构造函数,重载赋值操作符,方法get()
- 类赋值操作符和复制构造函数
- 影响正确性的move构造函数/赋值操作符示例
- 如果没有定义Move语义(Move构造函数和Move赋值操作符),编译器是否默认优化
- 即使类没有定义构造函数,也不能在类上调用c++默认的move赋值操作符
- 复制构造函数和赋值操作符都被调用
- 与智能指针相关的c++移动语义与复制构造函数和赋值操作符
- 为什么不是只有一个?复制构造函数和赋值操作符
- c++析构函数、复制构造函数和赋值操作符实践考试
- 为什么这里需要构造函数和赋值操作符
- 赋值给构造函数中的常量变量
- 成员初始化列表vs赋值/复制构造函数(在boost deadline_timer中)
- 将传递的对象赋值给构造函数中的成员对象