C++中如何在函数模板increase内使用重载的operator+运算符
Got it, let's work through this school assignment step by step. You need to implement overloaded operators for your Inductor class and call them inside a function template named increase—here's how to complete everything properly:
First, let's finish the Inductor class implementation based on the partial code you provided. We'll fill in the constructor, operator overloads, and add helper methods to interact with the private inductance member:
#pragma once #include <iostream> using namespace std; class Inductor { friend ostream& operator<<(ostream&, const Inductor&); private: int inductance; double maxCurrent; public: int operator+(int add); int operator-(int sub); Inductor(int, double); // Helper methods to access/modify private inductance void setInductance(int newInd); int getInductance() const; }; // Constructor definition Inductor::Inductor(int ind, double maxCurr) : inductance(ind), maxCurrent(maxCurr) {} // Overloaded + operator: returns inductance + input value int Inductor::operator+(int add) { return inductance + add; } // Overloaded - operator: returns inductance - input value int Inductor::operator-(int sub) { return inductance - sub; } // Friend ostream operator to print Inductor details ostream& operator<<(ostream& os, const Inductor& inductor) { os << "Inductance: " << inductor.inductance << " mH, Max Current: " << inductor.maxCurrent << " A"; return os; } // Setter for inductance void Inductor::setInductance(int newInd) { inductance = newInd; } // Getter for inductance int Inductor::getInductance() const { return inductance; }
Next, let's build the increase function template. The requirement is to call the overloaded operator+ inside this template—we'll use it to calculate the new inductance value and update the object:
template <typename T> void increase(T& obj, int increment) { // Call the overloaded + operator to compute the new inductance int updatedInductance = obj + increment; // Update the object's inductance using the setter obj.setInductance(updatedInductance); // Optional: Print the result to verify the change cout << "After increase: " << obj << endl; }
Example Test Code
To see this in action, add a main function to test the implementation:
int main() { // Create an Inductor instance: 80mH, max current 3.0A Inductor coil(80, 3.0); cout << "Original state: " << coil << endl; // Use the increase template to add 40mH increase(coil, 40); // Add another 25mH increase(coil, 25); return 0; }
Quick Explanations
- We added
getInductanceandsetInductancebecause theinductancemember is private—this lets us safely update the object's state after using the overloadedoperator+. - The
increasetemplate is generic, so it could work with any class that has an overloadedoperator+accepting anintand a way to update its internal value (like thesetInductancemethod here). - The overloaded operators follow your class declaration exactly—returning an
intas specified.
内容的提问来源于stack exchange,提问作者Sarah Collins

