I just learned class and object today, couldn't even get the code compiled. could anyone help please? Thank you
I have three files: Product.h Product.cpp TestProduct.cpp
We haven't learned to put everything in a project yet. so for now, just just these three source files.
Thanks for the reply. Because today we haven't learned to create a project yet. So my professor said we should include "Product.cpp" to make it work. These three soure files are not in a project format.
1 F:\DPR226\Homework\PRODUCT\Product.cpp:1, from F:\DPR226\Homework\PRODUCT\testProduct.cpp In file included from F:\DPR226\Homework\PRODUCT\/Product.cpp:1, from F:\DPR226\Homework\PRODUCT\testProduct.cpp
That is get/set abuse there indeed. I only use them when I need access to a variable to be limited in some way. When you have simple getters and setters without any extra code in them besides that for getting and setting, you know you're abusing 'em. ;)
That said, if your instructor commanded you to do it, then I can still blame you for not standing up to him or her I guess Disch and I will go after him or her with a #define #divine shotgun.
#include <iostream>
usingnamespace std;
class SomeClass
{
int a;
int b;
int c;
void calculate()
{
cout << "calculating..." << endl;
c=a*a-b;
}
class IntProxy
{
int & ref;
SomeClass * psc;
public:
IntProxy(int & n,SomeClass * psc_):
ref(n),psc(psc_){}
operatorint(){return ref;}
intoperator=(int n)
{
ref=n;
psc->calculate();
return n;
}
};
public:
SomeClass(int a_, int b_):
a(a_),b(b_){calculate();}
IntProxy A() {return IntProxy(a,this);}
IntProxy B() {return IntProxy(b,this);}
int C() const {return c;}
};
int main()
{
cout << "creating some_object..." << endl;
SomeClass some_object(3,5);
cout << "\nprinting a and b members..." << endl;
int temp=some_object.A();
cout << temp << endl;
cout << some_object.B() << endl;
cout << "\nprinting c member..." << endl;
cout << some_object.C() << endl;
cout << "\nsetting a and b members..." << endl;
some_object.A()=4;
some_object.B()=1;
cout << "\nprinting c member..." << endl;
cout << some_object.C() << endl;
cout << "\nhit enter to quit..." << endl;
cin.get();
return 0;
}
[/vomit-proof suit]
The trick is to behave in one way when the return value is treated as an L-value and in another way when it is treated as an R-value (or, more properly, 'not as an L-value'). But to make that possible you have to wrap the return type in a custom type.
I added the safeguards in the file. Thanks kfmfe04
I know all the getters and setters here seem so unnecessary, but we t have to practice using them now. Not sure about the shotgun though, our professor is quite a nice guy :)