为应该能够创建4个类对象并使用模板函数调用不同数据类型的算术运算的类编写该程序。我的错误告诉我,我的Sum,Difference等函数不是我创建的模板类的成员。'Sum':不是'Type <Object>'的成员 - C++模板
这里是我的Type.h
#ifndef TYPE_H
#define TYPE_H
#include <iostream>
using namespace std;
template <typename Object>
class Type : public Print
{
public:
//Constructor
explicit Type(const Object & initValue = Object()) : storedValue(initValue){}
//Accessor and Mutator for storedValue
const Object & getValue() const;
void setValue(const Object & val);
//Additional Operations
void Sum(const Type<Object> & val);
void Difference(const Type<Object> & val);
void Product(const Type<Object> & val);
void Quotient(const Type<Object> & val);
private:
Object storedValue;
};
template <typename Object>
const Object & Type<Object>::getValue() const
{ return storedValue; }
template <typename Object>
void Type<Object>::setValue(const Object & val)
{ storedValue = val; }
template <typename Object>
void Type<Object>::Sum(const Type<Object> & val)
{
cout << "The sum of " << val << "and " << storedValue << "is " << val += storedValue << endl;
}
template <typename Object>
void Type<Object>::Difference(const Type<Object> & val)
{
cout << "The difference of " << val << "and " << storedValue << "is " << val -= storedValue << endl;
}
template <typename Object>
void Type<Object>::Product(const Type<Object> & val)
{
cout << "The product of " << val << "and " << storedValue << "is " << val *= storedValue << endl;
}
template <typename Object>
void Type<Object>::Quotient(const Type<Object> & val)
{
cout << "The quotient of " << val << "and " << storedValue << "is " << val /= storedValue << endl;
}
class Print
{
public:
void printHello();
};
void Print::printHello()
{
cout << "Hello" << endl;
}
#endif
代码这里是TypeMain.cpp代码:
#include <iostream>
#include "Type.h"
using namespace std;
int main()
{
//Starting with int operations
Type<int> num1(3);
Type<int> num2;
num2.setValue(4);
num2.Sum(num1);
num2.Difference(num1);
num2.Product(num1);
num2.Quotient(num1);
//Double operations
Type<double> num3(3.3);
Type<double> num4;
num4.setValue(4.4);
num4.Sum(num3);
num4.Difference(num3);
num4.Product(num3);
num4.Quotient(num3);
//Hello prints for each object
num1.printHello();
num2.printHello();
num3.printHello();
num4.printHello();
return 0;
}
编辑:我已经更新的代码是什么,我已经修复。我不再有传递变量的错误。我仍然有最初的错误,其中函数不是类型的成员
您有多个函数调用缺少它们的参数,那些函数不总是有正确的参数,您试图修改常量对象,并且在表达式周围缺少括号。 –
是的,我知道电话。代码的那部分还没有完成,我试图解决第一个错误,因为我转向那个。 – Sean
您应该创建一个[MCVE],以便我们可以为您提供帮助。我无法重现这个问题,而且我不知道其他问题是否真的会导致这个问题。 –