C++クラスメンバー関数はクラスのオブジェクトを返します
22579 ワード
//
#include
#include
using namespace std;
class A {
public:
A() {
x = 50;
for(int i=0; i<10; i++) {
arr[i]=0;
}
str1 = " str1";
str2=" str2";
cout<<" "<<endl;
}
void setArr() {
for(int i=0; i<10; i++) {
arr[i]=i*i+100;
}
}
A(int x1,string s1,string s2) {
x = x1;
str1 = s1;
str2 = s2;
cout<<" "<<endl;
}
string getStr1() {
return str1;
}
string getStr2() {
return str2;
}
//
A *Add_ptr(A &p) {
cout<<" :"<<endl;
A *temp=new A;
temp->x = p.x+x;
temp->str1 = p.str1+str1;
temp->str2=p.str2+str2;
for(int i=0; i<10; i++) {
temp->arr[i]=p.arr[i]+arr[i];
}
return temp;
}
A(A &p) {
x = p.x;
str1 = p.str1;
str2 = p.str2;
for(int i=0; i<10; i++) {
arr[i]=p.arr[i];
}
cout<<" "<<endl;
}
//
A Add(A &p) {
A temp;
temp.x = x+p.x;
temp.str1=str1+p.str1;
temp.str2 = str2+p.str2;
for(int i=0; i<10; i++) {
temp.arr[i]=p.arr[i]+arr[i];
}
return temp;
}
//
A &Add_test(A &p){
x += p.x;
str1 += p.str1;
str2 += p.str2;
for(int i=0; i<10; i++) {
arr[i] += p.arr[i];
}
return *this;
}
//
void AddTest(A &p){
p.x += x;
p.str1 += str1;
p.str2 += str2;
for(int i=0; i<10; i++) {
p.arr[i] += arr[i];
}
}
A getA() {
A p(11,"str1","str2");
for(int i=0; i<10; i++) {
p.arr[i]=0;
}
return p;
}
//
A &operator=(A &p) {
cout<<" "<<endl;
x = p.x;
str1 = p.str1;
str2 = p.str2;
return *this;
}
//
friend ostream &operator<<(ostream &out,A &p) {
out<<" "<<endl;
out<<p.x<<endl<<p.str1<<endl<<p.str2<<endl;
for(int i=0; i<10; i++) {
out<<p.arr[i]<<"\t";
}
out<<endl;
return out;
}
void print() {
cout<<"print "<<endl;
cout<<x<<endl<<str1<<endl<<str2<<endl;
for(int i=0; i<10; i++) {
cout<<arr[i]<<"\t";
}
cout<<endl;
}
private :
int x;
int arr[10];
string str1;
string str2;
};
//
//
void test_1() {
// 1. p.Add(q) ,
// A(A &p) ,
// s ,
cout<<" :"<<endl;
A p;
A q;
p.setArr();
q.setArr();
// 2. , ; ,
// A s = p.Add(q);
// cout<<s;
//
p.Add(q).print();
cout<<endl;
}
//
//
void test_2() {
cout<<" :"<<endl;
A p;
A q;
p.setArr();
q.setArr();
//
A *ptr = p.Add_ptr(q);
cout<<*ptr;
cout<<ptr->getStr1()<<endl;
cout<<endl;
//
delete ptr;
}
//
//
void test_3() {
cout<<" :"<<endl;
A p;
//
A q = p;
A s;
//
s = q;
s.setArr();
cout<<s<<endl;
}
//
//
void test_4(){
cout<<" :"<<endl;
A p;
A q;
p.setArr();
q.setArr();
// A &Add_test(A &p)
A r = p.Add_test(q);
//
cout<<r<<endl;
}
//
void test_5(){
A p;
A q;
p.setArr();
q.setArr();
// q
p.AddTest(q);
cout<<q<<endl;
}
int main() {
test_1();
test_2();
test_3();
test_4();
test_5();
}