c++ - 使用另一个用户定义数据类型作为参数的用户定义数据类型

标签 c++

我无法让编译器接受我下面定义的用户数据类型 (Term),它接受另一种用户数据类型 (Rational) 作为参数。任何关于如何使这项工作的建议都很棒!

#ifndef _TERM_H
#define _TERM_H

#include "Rational.h"

using namespace std;

class Term {

public:

    //constructors
    Term( const Rational &a, const int &b)
    { 
        this->coefficient = a;
        this->exponent = b;
    }

    Term(){}

    ~Term () {}

    //print the Rational
    void print()const 
    {
        cout << coefficient << " x^"  << exponent << endl;
    }

private:

    Rational *coefficient, *a;
    int exponent, b;
};

#endif

#ifndef _TERM_H
#define _TERM_H

using namespace std;

class Rational {

public:

    //constructors
    Rational( const int &a, const int &b){
        if (a != 0)
            if (b != 0)
                this->numerator = a;
            this->denominator = b;
    }

    //print the Rational
    void print()const {
        cout << numerator << "/" << denominator << endl;
    } 

    //add 2 Rationals 
    void add(const Rational &a, const Rational &b){
        numerator = ((a.numerator * b.denominator)+(b.numerator*a.denominator));
        denominator = (a.denominator*b.denominator);  
    }

 ...

    private:
     int a, b, numerator, denominator;
};

#endif

我不断收到以下错误消息。

Term.h(30):错误 C2440:“=”:无法从“const Rational”转换为“Rational *” 1> 没有可用的可以执行此转换的用户定义转换运算符,或者无法调用该运算符 ========== 构建:0 成功,1 失败,0 最新,0 跳过 ==========

最佳答案

首先,将coefficient的定义修改为:

const Rational& coefficient;

然后将构造函数更改为:

Term (const Rational& a, const int& b)
  : coefficient (a), exponent (b)
{
}

关于c++ - 使用另一个用户定义数据类型作为参数的用户定义数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4296494/

相关文章:

c++ - 为什么构造函数不能推断模板参数?

c++ - 用opencv获取帧视频

c++ - 在SGI STL的实现中,文件STL_alloc.h中模板参数 "int inst"的作用是什么?

c++ - cin 不会在循环中工作

c++ ifstream,从文件读取崩溃

c++ - GL_DEPTH_TEST 在 OpenGL 3.3 中不起作用

c++ - 无法在 Qt 中运行 freetype

c++ - 我如何制作原始类型 C++ 的拷贝?

c++ - #ifndef 没有按预期工作

c++ - dynamic_cast 模板类 "invalid target type for dynamic_cast"