Re: 請教C++的this
※ 引述《quota@kkcity.com.tw (我要出清)》之銘言:
> #include <iostream>
> #include <cstdlib>
> using namespace std;
> class work
> {
> public:
> int Id;
> char name[20];
> work() {
> Id = 0;
> strcpy(name, "ZZZ"); //指定name初值
> }
> void output() {
> cout << this->Id << endl;
> cout << (*this).Id << endl;
> }
> };
> int main(void)
> {
> work work1;
> work1.Id=5;
> //work1.name="quota123";
> work1.output();
> system("pause");
> return 0;
> }
> 請教一下 以上程式的
> this->Id 與(*this).Id 我在網路上看到陳老師的網頁 他是這樣說明:
> 「this」指標代表目前這個物件的指標;
> 「*this」則代表目前這個物件的內容
> 可是.為何我這裡得到的答案都是5呢?
你可能必須先學會所有 operator 的意義才行,
ptr->member 只不過是 (*ptr).member 的另一種寫法,
你完全把問題重心看偏了。
> 另外我想問.. strcpy這一行程式是我看到範例原本就有的
> 可是 如果我想要給他資料
> 比如work1.name="quota123";
> 卻會出現錯誤
> 請問..work class內的這個成員 我該如何使用呢?
也是用 strcpy(work1.name, "quota123"); 設值,
C-style string 就該照 C-style string 的規則玩,
如果你還不熟,
那建議你最好先搞懂它,
不過也建議你在 C++ 就多用 C++ 的 string,
往後想做其它事情也比較簡單。
--
Name: Tseng, Ling-hua E-mail Address: uranus@it.muds.net
School: National Tsing Hua University Department: Computer Science
Interesting: C++, Compiler, PL/PD, OS, VM, Large-scale software design
Researching: Undecided
Homepage: https://it.muds.net/~uranus
--
╔═══╗ ┼────────────────────────╮
║狂狷 ║ │* Origin:[ 狂 狷 年 少 ] whshs.cs.nccu.edu.tw ╰─╮
║ 年少║ ┼╮ < IP:140.119.164.252 > ╰─╮
╚╦═╦╝ ╰ * From:61-230-217-167.dynamic.hinet.net
─╨─╨─ KGBBS ─ ◎ 遨翔"BBS"的狂狷不馴;屬於年少的輕狂色彩 ◎
推
11/03 12:51, , 1F
11/03 12:51, 1F
討論串 (同標題文章)
完整討論串 (本文為第 3 之 3 篇):
1
1
Programming 近期熱門文章
PTT數位生活區 即時熱門文章