C++関数は複数のパラメータを返します

2337 ワード

: , , , ? , 。 ! :

struct Result{
    int shang;
    int yu;
};

struct Result div(int a,int b){
    struct Result ret;
    ret.shang = a/b;
    ret.yu = a%b;
}

struct Result r = div(33432,44);

まず Resultを し,また divを し, に を び した.
をタイプとする は、 にキーワードstructを ける があります. っていなくてもいいと うなら、typedefでstruct Resultの を る があります.この は としてResultですが、これでキーワードstructを くことができます(ソースファイルが.cppで.cではなく.cppであれば、typedefでなくてもキーワードstructを くことができます).
typedef struct Result{
    int shang;
    int yu;
}Result;

Result div(int a,int b){
    struct Result ret;
    ret.shang = a/b;
    ret.yu = a%b;
}

Result r = div(33432,44);
は、 が れる が であることを ることができます. する を にして、 として します.
は、システムの のタイプint、longなどのようにカスタムタイプです.
の にアクセスする は「.」です. の をメンバー と びます.
は のパラメータとしても できます.
1つの で のパラメータを す がある は、 の2つの があります.
1つ の は、 り を き みパラメータとして することです.
2つ の は、 を し、その を すポインタを すことです.
#include 
#include 
using namespace std;

void fun(int &a, char &b, string &c)
{
	a = 1;
	b = 'b';
	c = "test";
}

int main()
{
	int a;
	char b;
	string c;
	fun(a,b,c);
	cout << a << " " << b << " " << c << endl;
}

1つ の は、 り を き みパラメータとして することです.
#include
#include
using namespace std;
struct result
{
 int a;
 char b;
 string c;
};
result * fun()
{
 result *test=new result;
 test->a = 1;
 test->b = 'b';
 test->c = "test";
 return test;
}
int main()
{
 result *test;
 test=fun();
 cout << test->a << ""<< test->b << ""<< test->c << endl;
 delete test;
 return 1;
}
2つ の は、 を し、その を すポインタを すことです.
とは
1つの を します:1つの を いて、2つの を して いて、 に と に ることを して、どのように きますか?
の り は1つしかないことを っていますが、 に2つの を すことは です.しかし、 で になりました!コードは のとおりです.