好的,所以我试图让我的程序工作,看起来有些不对劲,但我不知道为什么。你能不能看看它,告诉我什么错了?
问题是:减法无效:c
这是Main函数(NumberProject.cpp)的代码:
// NumberProject.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
#include "Number.h"
using namespace std;
int main( ) {
// Variable and Object Declarations
char answer;
bool goAgain = true;
int integerValue;
Number numberA; // Invoke the default constructor.
Number numberB; // Invoke the default constructor.
// User loop
while ( goAgain ) {
cout << "Enter an integer: ";
cin >> integerValue;
numberA.Set( integerValue );
cout << "Enter an integer: ";
cin >> integerValue;
numberB.Set( integerValue );
cout << endl;
// Addition
numberA.Add( numberB );
cout << "Addition: ";
numberA.Output( );
// Subtraction
numberA.Subtract( numberB );
cout << "Subtraction: ";
numberB.Output( );
// User loop termination code.
cout << "Would you like to continue? (y/n)" << endl;
cin >> answer;
if ( answer == 'n' )
goAgain = false;
} // while
return 0;
} // Function main( )
Number.cpp(class):
#include "StdAfx.h"
#include "math.h" // Needed for sqrt and pow.
#include <string>
#include <iostream>
#include "Number.h"
using namespace std;
Number::Number( void ) {
number = 0;
}
Number::Number( int integerValue ) {
number = integerValue;
}
Number::~Number( void ) {
}
int Number::Get( ) {
return number;
}
void Number::Set( int integerValue ) {
number = integerValue;
}
void Number::Output( ) {
cout << number << endl;
cout << endl;
}
void Number::Add( Number otherNumber ) {
number = number + otherNumber.Get();
}
void Number::Subtract( Number otherNumber ) {
number = number - otherNumber.Get();
}
Number.h:
#pragma once
class Number {
public:
Number( void );
Number( int );
~Number( void );
int Number::Get( ); // Accessor
void Number::Set( int ); // Mutator
void Number::Output();
void Number::Add( Number );
void Number::Subtract( Number );
private:
int number;
}; // Class Number
答案 0 :(得分:4)
numberA.Subtract( numberB );
cout << "Subtraction: ";
numberB.Output( );
您输出的号码错误。您想要打印numberA
。
numberA.Subtract( numberB );
cout << "Subtraction: ";
numberA.Output( ); // <-- here
此外,当您进行初始添加时,您正在更新numberA
的内存中值;当你去做减法时,numberA
已经有numberA
+ numberB
的总和。
因此,当您执行numberA
- numberB
时,您将不得不保留numberA
值的副本,而不是保存它的值。试试这个:
int Number::Add(Number otherNumber) {
return number + otherNumber.Get();
}
int Number::Subtract(Number otherNumber) {
return number - otherNumber.Get();
}