Error:E0415 no suitable constructor exists to convert from “int“ to “Rational“

Error:E0415 no suitable constructor exists to convert from “int“ to “Rational“,第1张

场景:

这个问题是因为缺少对于的构造函数或者是该构造函数被声明为explicit。

可以参考下面这个场景。

#include 

using std::cout;
using std::endl;

class Rational1
{
public:
	Rational1(int n = 0, int d = 1):num(n), den(d)
	{
		cout << __func__ << "(" << num << "/" << den << ")" << endl;
	}

public:
	int num; // 被除数
	int den; // 除数
};

class Rational2
{
public:
	explicit Rational2(int n = 0, int d = 1) :num(n), den(d)
	{
		cout << __func__ << "(" << num << "/" << den << ")" << endl;
	}

public:
	int num; // 被除数
	int den; // 除数
};

void Display1(Rational1 r)
{
	cout << __func__ << endl;
}

void Display2(Rational2 r)
{
	cout << __func__ << endl;
}


int main()
{
	Rational1 r1 = 11;
	Rational1 r2(11);
	Rational2 r3 = 11; // error E0415
	Rational2 r4(11);

	Display1(1);
	Display2(2); // error  E0415
	return 0;
}
explicit关键字

1、指定构造函数或转换函数 (C++11起)为显式, 即它不能用于隐式转换和复制初始化.
2、explicit 可以与常量表达式一同使用. 函数若且唯若该常量表达式求值为 true 才为显式. (C++20起)

问题描述

Error:E0415 no suitable constructor exists to convert from “int“ to “Rational“

解决方案:

1. 自己实现对应的构造函数。(推荐)
2. 删掉被 explicit关键字修饰的构造函数。(不推荐)

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/2889579.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-09-14
下一篇 2022-09-14

发表评论

登录后才能评论

评论列表(0条)

保存