const A&fun(const A&a)const{}の理解

3204 ワード

くだらないことは言わないで、直接料理を出します.
#include 
using namespace std;

class A
{
public:
	int x;
	A(A&)
	{
		cout << "copy constructor" << endl;
	}

	void fun() const
	{
		x = 1; // error,   const               
	}
};

int main()
{
	return 0;
}

続行:
#include 
using namespace std;

class A
{
public:
	int x;
	
	A()
	{
	
	}

	A(A&)
	{
		cout << "copy constructor" << endl;
	}

	void fun(A a) //      
	{
	}
};

int main()
{
	A a, b;
	a.fun(b); //            

	return 0;
}

続行:
#include 
using namespace std;

class A
{
public:
	int x;
	
	A()
	{
	
	}

	A(A&)
	{
		cout << "copy constructor" << endl;
	}

	void fun(A& a) //   
	{
	}
};

int main()
{
	A a, b;
	a.fun(b); //            

	return 0;
}

続行:
#include 
using namespace std;

class A
{
public:
	int x;
	
	A()
	{
	
	}

	A(A&)
	{
		cout << "copy constructor" << endl;
	}

	void fun(const A& a) 
	{
		a.x = 100; // error,  const  ,   a.x      
	}
};

int main()
{
	A a, b;
	a.fun(b);

	return 0;
}

     go on:
#include 
using namespace std;

class A
{
public:
	int x;
	
	A()
	{
	
	}

	A(A&)
	{
		cout << "copy constructor" << endl;
	}

	A fun() 
	{
		A aa;
		return aa; 
	}
};

int main()
{
	A a;
	a.fun(); //            

	return 0;
}
      
     go on:
#include 
using namespace std;

class A
{
public:
	int x;
	
	A()
	{
	
	}

	A(A&)
	{
		cout << "copy constructor" << endl;
	}

	A& fun() 
	{
		A aa;
		return aa; // danger,              ,          
	}
};

int main()
{
	A a;
	a.fun(); //            

	return 0;
}
     go on:
#include 
using namespace std;

class A
{
public:
	int x;
	
	A()
	{
	
	}

	A(A&)
	{
		cout << "copy constructor" << endl;
	}

	A& fun(A& a) 
	{
		return a;
	}
};

int main()
{
	A a, b;
	a.fun(b).x = 1; // ok

	return 0;
}
    
      go on:
#include 
using namespace std;

class A
{
public:
	int x;
	
	A()
	{
	
	}

	A(A&)
	{
		cout << "copy constructor" << endl;
	}

	const A& fun(A& a) 
	{
		return a;
	}
};

int main()
{
	A a, b;
	a.fun(b).x = 1; // error,     

	return 0;
}

    go on:
#include 
using namespace std;

class A
{
public:
	int x;
	
	A()
	{
	
	}

	A(A&)
	{
		cout << "copy constructor" << endl;
	}

	A& fun(const A& a) 
	{
		return a;
	}
};

int main()
{
	A a, b;
	a.fun(b).x = 1; // error

	return 0;
}

最後の料理:
#include 
using namespace std;

class A
{
public:
	int x;
	
	A()
	{
	
	}

	A(A&)
	{
		cout << "copy constructor" << endl;
	}

	const A& fun(const A& a) const
	{
		return *this;
	}
};

// ok
int main()
{
	A a, b;
	a.fun(b);

	return 0;
}