ページ 11

クラスをポインタで受け取った場合の。。。

Posted: 2015年9月15日(火) 19:51
by 豆電球
はじめまして、よろしくお願いします。
9月5日にVS2013Expressを入れたばかりの初心者です。
件名を上手く付けられなかったのですが、下記のコードで、
*pS は意味のないただの文字列でもないし、sを表すオブジェクトでもないけど、
&でアドレスは取得できる。
*pSはどんな内容のもので、C、C++で何と呼ばれるものなのかと
疑問に思ってしまいました。

コード:

#include<iostream>
using namespace std;

class Student
{
public:
	int semesterHours;
};

void someFn(Student *pS);

void someFn(Student *pS)
{
	pS->semesterHours = 10;		//	pSはStudentクラスのオブジェクトsのポインタ
	//*pS.semesterHours = 20;		//	*pSはオブジェクトsを表さない?
	(&(*pS))->semesterHours = 30;	//	しかし、*pSからsのポインタは得られる。		
							//	*pSはsの何かではあるけど、何なのか疑問になってしまいました。
}

int main()
{
	Student s;
	someFn(&s);

	cout << s.semesterHours << endl;

	system("pause");

	return 0;

}

Re: クラスをポインタで受け取った場合の。。。

Posted: 2015年9月15日(火) 22:18
by YuO
豆電球 さんが書きました:*pS は意味のないただの文字列でもないし、sを表すオブジェクトでもないけど、
&でアドレスは取得できる。
*pSはどんな内容のもので、C、C++で何と呼ばれるものなのかと
疑問に思ってしまいました。
pSがStudent型へのポインタ型のオブジェクトであるならば,*pSはpSが指し示すStudent型のオブジェクト (のlvalue値) です。
豆電球 さんが書きました:

コード:

	//*pS.semesterHours = 20;		//	*pSはオブジェクトsを表さない?
これは,単項*演算子よりも,.演算子の方が優先順位が高いため,*(pS.semesterHours) = 20;と解釈されます。
pSはポインタ型ですから,.演算子を適用できず,コンパイルエラーになります。
(*pS).semesterHours = 20;と,優先順位を明示することによって,*pSのメンバーへアクセスができます。

Re: クラスをポインタで受け取った場合の。。。

Posted: 2015年9月15日(火) 22:19
by みけCAT
N3337 ← C++の規格書に近い文章です。
N3337 3.10 Lvalues and rvalues さんが書きました:An lvalue (so called, historically, because lvalues could appear on the left-hand side of an assignment
expression) designates a function or an object.
N3337 5.3.1 Unary operators さんが書きました:1 The unary * operator performs indirection: the expression to which it is applied shall be a pointer to an
object type, or a pointer to a function type and the result is an lvalue referring to the object or function
to which the expression points. If the type of the expression is “pointer to T,” the type of the result is “T.”
(略)
3 The result of the unary & operator is a pointer to its operand.
*pSはpSに間接演算子を適用した結果であり、pSが指しているオブジェクトであるsを表すlvalue(sを明確に示している?)のようです。

Re: クラスをポインタで受け取った場合の。。。

Posted: 2015年9月16日(水) 06:06
by 豆電球
YuOさん、みけCATさん、ご回答ありがとうございます。
お二人のおかげですっきりする事ができました。
まだ、始めたばかりで掘り下げ方の足りない質問をしてしまうかもしれませんが
これからもよろしくお願い致します。
ありがとうございました。