【发布时间】:2020-04-11 00:11:03
【问题描述】:
问题
我有一个 Deck 类,它是 52 个 Card 对象的容器。 Deck 派生自另一个名为 CardCollection 的类(因为我希望其他地方的类似卡片组不是一副完整的卡片)。我的问题是我可以使用
Deck 对象
Deck deck();
但是当我使用时
Deck deck = Deck();
Clang-tidy(在 CLion 中)抱怨 Candidate constructor (the implicit copy constructor) not viable: expects an l-value for 1st argument。我的理解(基于this问题是这两种实例化方式基本相同,但由于一种会导致警告
代码
我将只粘贴这些类声明的构造函数,以防止出现“墙-o-text”问题。
//Card.h
class Card {
public:
int rank;
basic_string<char> suit;
Card(int r, std::string s); // rank and suit
~Card();
//...
}
// CardCollection.h
#include <vector>
#include "Card.h"
class CardCollection {
protected:
vector<Game::Card> _cards;
public:
CardCollection();
~CardCollection();
CardCollection(CardCollection &other);
explicit CardCollection(int n);
explicit CardCollection(vector<Game::Card> &cards);
//...
和
// Deck.h
#include "Card.h"
#include <vector>
#include "CardCollection.h"
class Deck : public CardCollection {
public:
Deck();
~Deck();
explicit Deck(vector<Game::Card> &cards);
Deck * shuffle();
//...
};
【问题讨论】:
-
你需要实现一个拷贝构造函数。如果您还想要
deck = Deck()(即,不在声明时),那么还需要一个赋值运算符。 -
啊,我还以为是从
CardCollection派生出来的? -
而
Deck deck();是一个函数声明。 -
你的复制构造函数也应该是
CardCollection(const CardCollection& other); -
构造函数不是继承的,所以即使超类已经有拷贝构造函数,你也需要在子类中显式定义拷贝构造函数。
标签: c++ class oop instantiation copy-constructor