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

场景:

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

可以参考下面这个场景。

#include <iostream>

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关键字修饰的构造函数。(不推荐)


C++常见错误

fatal error C1189: #error: STL1003: Unexpected compiler, expected C++ compiler

error C2041: illegal digit ‘9‘ for base ‘8‘ | error C2059: syntax error: ‘bad suffix on number‘

Error:QSqlDatabase: QMYSQL driver not loaded (Qt+C++ 找不到mysql的驱动)

Qt5Error:msvc-version.conf loaded but QMAKE_MSC_VER ins‘t set

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

Error:error C2601: ‘b‘ : local function definitions are illegal error C2063: ‘b‘ : not a function


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林夕07

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值