爲應該能夠創建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],以便我們可以爲您提供幫助。我無法重現這個問題,而且我不知道其他問題是否真的會導致這個問題。 –