[英]C++ can't implement default constructor
I have the following class: 我有以下课程:
class Fraction {
private:
int x;
int y;
public:
// Constructors
Fraction(long x = 0, long y = 1);
Fraction(const Fraction&)=default;//here is the problem
virtual ~Fraction();
};
I'm trying to disable default C++ constructor to implement my own (I intend to use it for copy). 我试图禁用默认的C ++构造函数来实现自己的(我打算将其用于复制)。 So, I declared it as a default.
因此,我将其声明为默认值。 But, when I'm trying to implement it:
但是,当我尝试实现它时:
Fraction::Fraction(const Fraction&){}
Compiler throws the following error at me: 编译器向我抛出以下错误:
./src/Fraction.cpp:16:1: error: definition of explicitly-defaulted 'Fraction::Fraction(const Fraction&)' Fraction::Fraction(const Fraction&){ ^ In file included from ../src/Fraction.cpp:8:0: ../src/Fraction.h:22:2: error: 'Fraction::Fraction(const Fraction&)' explicitly defaulted here Fraction(const Fraction&)=default;
./src/Fraction.cpp:16:1:错误:明确默认的'Fraction :: Fraction(const Fraction&)'的定义Fraction :: Fraction(const Fraction&){^在../src/Fraction中包含的文件中。 cpp:8:0:../src/Fraction.h:22:2:错误:'Fraction :: Fraction(const Fraction&)'在这里明确默认为Fraction(const Fraction&)= default;
Is there any way to fix it? 有什么办法可以解决? What I'm doing wrong ?
我做错了什么? I found some articles about defaults, but nothing that can help me fix these errors.
我找到了一些有关默认值的文章,但是没有什么可以帮助我解决这些错误。
= default
tells the compiler to use the default implementation. = default
告诉编译器使用默认实现。 This also means that you cannot provide your own . 这也意味着您无法提供自己的 。 If you don't want the compiler to create one, simply remove
= default
: 如果您不希望编译器创建一个,只需删除
= default
:
class Fraction {
// ...
Fraction(const Fraction&); // NO =default
};
By the way, the "default constructor" is the one that's called when you don't provide any arguments, eg 顺便说一句,“默认构造函数”是当您不提供任何参数时调用的那个,例如
Fraction my_frac; // default constructor called
If you want to disable the default constructor, use =delete
: 如果要禁用默认构造函数,请使用
=delete
:
class Fraction{
public:
Fraction() = delete;
}
Keep in mind that your current Fraction(long, long)
provides default arguments, so it's eligible as a default constructor. 请记住,您当前的
Fraction(long, long)
提供默认参数,因此可以用作默认构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.