gpt4 book ai didi

c++ - 数值包装器

转载 作者:太空宇宙 更新时间:2023-11-04 11:36:34 25 4
gpt4 key购买 nike

我正在尝试编写一个包装数值的 C++ 程序,我正在通过编写一个将处理两个简单函数和一个运算符重载函数的父类(super class)来实现这一点。这是我到目前为止的代码:

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



template <class T>
class Number {
protected:
T number;

public:
Number(T num) {
number = num;
}

string mytype() {
return typeid(number).name();
}

string what_am_i() {
ostringstream oss;
oss << "I am " << Number<T>::mytype() << " and my value is " << number;
return oss.str();
}

Number operator+ (Number an) {
Number brandNew = NULL;
brandNew.number = number + an.number;
return brandNew;
}
};


class MyInt : public Number<int> {
public:
MyInt() : Number<int>(0) {};
MyInt(int num) : Number<int>(num) {}
MyInt(const Number<int> &x) : Number<int>(x) {}
};



class MyFloat : public Number<float> {
public:
MyFloat() : Number<float>(0){};
MyFloat(float num) : Number(num){}
MyFloat(const Number<float> &x) : Number<float>(x) {}
};

class MyDouble : public Number<double> {
public:
MyDouble() : Number<double>(0){};
MyDouble(double num) : Number(num){}
MyDouble(const Number<double> &x) : Number<double>(x) {}
};

在主函数中我想做这样的事情:

void main() {       
MyInt two = 2;
MyFloat flo = 5.0f;
MyDouble md3 = flo + two;
}

并希望 md3 为 15.00000,到目前为止,添加两个相同类型的对象效果很好,但是当我尝试添加 MyInt 和 MyFloat 时,编译器不喜欢它。有谁知道我该如何实现它?

最佳答案

您必须为模板类添加类型运算符:

operator T()
{
return number;
}

这是我测试并运行的编译代码:

template <class T>
class Number {
protected:
T number;

public:
Number(T num) {
number = num;
}

string mytype() {
return typeid(number).name();
}

string what_am_i() {
ostringstream oss;
oss << "I am " << Number<T>::mytype() << " and my value is " << number;
return oss.str();
}

Number operator+ (Number an) {
Number brandNew = NULL;
brandNew.number = number + an.number;
return brandNew;
}

operator T()
{
return number;
}
};

我试图更好地解释它为什么有效。当您对加号运算符进行重载时,您希望执行如下操作:left_value + right_value,其中 right_value 是加号运算符的“an”参数。

现在要获得对象“an”的正确值,您必须重载“类型运算符”,如果您不在 Number 类中重载此运算符,则无法将其读取为正确值。以下示例适用于 operator=(),但也适用于 operator+():

template<typename T>
class Number
{
T value;

public:

T operator=(T arg) // Assignment, your class is seen as left operand
{
value = arg;
}

operator T() // Getting, your class is seen as right operand
{
return value;
}
}

Number<int> A; // define a new class Number as int
Number<double> B; // define a new class Number as double

A = B; // is same to A.operator=( B.double() );

将A赋为左值称为Number类的运算符“operator=()”,将B取为右值称为Number类的“运算符T()”

现在翻译成:

// instance of the operator = of the class Number<int>
int operator=(int arg)
{
}


// instance of the Operator T of the class Number<double>
operator double()
{
}

此翻译模拟了 A 和 B 对象的以下语义:

int A;
double B;

A = B;

再见安杰洛

关于c++ - 数值包装器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22881666/

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