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

猜你喜欢

转载自blog.csdn.net/qq_45254369/article/details/126840796