Let me consider the following example!
namespace nSpace {
class Addition {
int val1;
int val2;
public:
Addition(int firstVal, int secondVal) {
this.val1 = firstVal;
this.val开发者_如何学Python2 = secondval;
}
void sum() {
cout<<"sum of val1 and val2 = " <<this.val1 + this.val2<<"\n";
}
};
Addition Addobj = new Addition(2, 3); // Is it possible ? if not, any other way ?
Addobj.sum();
}
If not, do let me know the reason.
Thank you!
This isn't Java, you just need the line
Addition Addobj(2, 3);
like rlbond said, or if you REALLY want "to be new" :)
nSpace::Addition &Addobj = *(new nSpace::Addition(2, 3));
Addobj.sum();
//don't forget to delete Addobj! (delete &Addobj;)
yes It is possible, Only the objects at namespace level is possible, but you can't have a executing statements,
Addition Addobj = Addition(2, 3); // Is valid
Addobj.sum(); //not valid
//You got few error, below is working code
namespace nSpace {
class Addition {
int val1;
int val2;
public:
Addition(int firstVal, int secondVal) {
this->val1 = firstVal;
this->val2 = secondVal;
cout<<"sum of val1 and val2 = ";
}
void sum() {
cout<<"sum of val1 and val2 = " <<this->val1 + this->val2<<"\n";
}
} ;
Addition Addobj = Addition(2, 3); // Is it possible ? yes
//Addobj->sum();// this does not work
}
void main()
{
}
This is legal outside a function:
Addition *Addobj = new Addition(2, 3);
because that is considered a variable definition and it may be done outside of a function (it will define a global variable). Note that since you are using new, the type of variable actually has to be a pointer;
This on the other hand is not legal outside a function
Addobj->sum(); // Illegal outside a function
The reason why is that this is a statement. Both statements and expressions are only legal inside a function.
You cant with posted code. the reason is simple, you are not within any function body to execute ur code. the new() operator and function sum() cannot be called as lhs at global level
精彩评论