gpt4 book ai didi

c++ - 前向声明后类型类的使用无效

转载 作者:行者123 更新时间:2023-11-28 05:51:08 25 4
gpt4 key购买 nike

我编写此程序是为了演示 C++ 中的双重分派(dispatch)。但它显示无效使用类型类,即使我已经转发声明了我的类。有什么方法可以在不编写单独的头文件的情况下纠正这个问题。

#include <iostream>
#include <string>
using namespace std;

class Number;
class Integer;
class Rational;

class Number{
public:
int num, den;
virtual void add(Number&) = 0;
virtual void addInteger(Integer&) = 0;
virtual void addRational(Rational&) = 0;
virtual string toString() = 0;
};



class Rational : public Number{
void addInteger(Integer& i){
this->num = this->num + i.num*this->den;
this->den = this->den;
cout << this->num << "/" << this->den;
}

void addRational(Rational &r){
this->num = this->num*r.den + this->den*r.num;
this->den = this->den*r.den;
cout << this->num << "/" << this->den;
}

public:
void add(Number& n){
n.addRational(*this);
}

Rational(int n, int d){
this->num = n;
this->den = d;
}
};


class Integer : public Number{
void addInteger(Integer& i){
this->num += i.num;
this->den = 1;
cout << this->num;
}

void addRational(Rational& r){
this->num = this->num*r.den + r.num;
this->den = r.den;
cout << "this->num" << "/" << this->den;
}

public:

void add(Number& n){
n.addInteger(*this);
}

Integer(int n){
this->num = n;
this->den = 1;
}
};



int main(){
cout << "Helo World";
return 0;
}

最佳答案

您只需要将函数声明与其定义分开即可。函数定义需要出现在它们使用的类定义之后。

示例代码

#include <iostream>
#include <string>
using namespace std;

class Number;
class Integer;
class Rational;

class Number
{
public:
int num, den;
virtual void add(Number&) = 0;
virtual void addInteger(Integer&) = 0;
virtual void addRational(Rational&) = 0;
virtual string toString() = 0;
};

class Rational : public Number
{
void addInteger(Integer& i);

void addRational(Rational &r);

public:
void add(Number& n)
{
n.addRational(*this);
}

Rational(int n, int d)
{
this->num = n;
this->den = d;
}
};

class Integer : public Number
{
void addInteger(Integer& i);

void addRational(Rational& r);

public:
void add(Number& n)
{
n.addInteger(*this);
}

Integer(int n)
{
this->num = n;
this->den = 1;
}
};

void Rational::addInteger(Integer& i)
{
this->num = this->num + i.num*this->den;
this->den = this->den;
cout << this->num << "/" << this->den;
}

void Rational::addRational(Rational &r)
{
this->num = this->num*r.den + this->den*r.num;
this->den = this->den*r.den;
cout << this->num << "/" << this->den;
}

void Integer::addInteger(Integer& i)
{
this->num += i.num;
this->den = 1;
cout << this->num;
}

void Integer::addRational(Rational& r)
{
this->num = this->num*r.den + r.num;
this->den = r.den;
cout << "this->num" << "/" << this->den;
}

int main()
{
cout << "Helo World";
return 0;
}

Live Example

关于c++ - 前向声明后类型类的使用无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35226535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com