[英]What does '->' mean when trying to forward-declare?
我剛剛開始試用C ++。 當我試圖從另一個文件轉發聲明這個類時,我一直遇到這個錯誤:在'girl'中請求成員'get_posx',這是指針類型'Vex *'(也許你想用' - >'?)
這些是我在Qt-Creator Plain C ++項目中包含的兩個文件:
main.cpp中:
#include <iostream>
using namespace std;
class Vex; //Declares Vex class
class Obj //Object class
{
int x, y;
public:
void set_pos (int,int);
void move (int, int);
int get_posx() {return x;}
int get_posy() {return y;}
};
void Obj::set_pos (int pos_x, int pos_y) //Sets X and Y of Obj
{
x = pos_x;
y = pos_y;
}
void Obj::move (int pos_x, int pos_y) //Changes X and Y of Obj
{
x += pos_x;
y += pos_y;
}
int main ()
{
Obj guy; //Guy as Obj class
Vex* girl; //Girl as (imported)Vex class
guy.set_pos (0,0);
while(true == true)
{
int tempx, tempy;
cout << girl.get_posx(); //Prints x pos. of girl
cout << "\nX Position: " << guy.get_posx() <<endl; //Prints x pos. of guy
cout << "Y Position: " << guy.get_posy() <<endl; //Prints y pos. of guy
cout << "\nX Change:" << endl;
cin >> tempx; //Asks for x change in guy pos.
cout << "Y Change:" << endl;
cin >> tempy; //Asks for y change in guy pos.
guy.move (tempx, tempy);
}
return 0;
}
s.cpp:
class Vex
{
int x, y;
public:
void exp();
int get_pos() {return x;}
};
void Vex::exp()
{
x = 0;
y = 0;
}
我在這里做錯了什么,什么是' - >',我該如何使用它?
我認為你最好先學習C ++,因為你似乎缺乏基礎知識; 沒有冒犯意味着,只是試圖幫助它。 您在腦海中存在一些誤解以及實施問題。 我甚至不知道從哪里開始。 讓我們看看:
堆和堆棧分配對象之間的差異(也就是指針與非指針)。
Vex* girl; //Girl as (imported)Vex class ... cout << girl.get_posx(); //Prints x pos. of girl
指針對象成員可以通過->
在C ++中訪問,因此您應該將代碼修改為:
cout << girl->get_posx(); //Prints x pos. of girl // ^^
什么時候可以使用前向聲明。
class Vex; //Declares Vex class
當您想要訪問類成員時,這還不夠。 您需要通過include指令包含類定義,如下所示:
#include "vex.h"
在源文件中聲明類似的類(aka .cpp)
這通常是錯誤的,盡管不是最終肯定的。 如果你這樣做,你將無法在不包含源文件的情況下輕松地重復使用它,這不是真正推薦的。
嚴格來說,C ++中沒有“import”這樣的東西。
Vex* girl; //Girl as (imported)Vex class // ^^^^^^^^
可以在其他編程語言(如python)中找到導入作為術語,但這些術語與包含的工作方式不同。
Overcommenting
這種評論不僅有點不全面,甚至毫無意義。 努力實現自我記錄的代碼。
你認為它與Qt有任何關聯。
它不是,即使你這樣標記它。 它是通用的(和基本的)C ++。
對於不更改成員的方法,不使用const。
對於在代碼中獲取成員這樣的事情,這是一種很好的做法,即:
int get_posx() const {return x;} // ^^^^^ int get_posy() const {return y;} // ^^^^^
......同樣地:
int get_pos() const {return x;} // ^^^^^
如何編寫一個阻塞永遠循環。
while(true == true)
雖然這有效,但這是荒謬的。
`while(1)`
或者干脆
`forever()`
在Qt會更優雅。
編碼風格不一致(例如空間使用)
void set_pos (int,int); // ^ ^ void move (int, int); // ^ ^ int get_posx() {return x;} // ^
不使用縮進
您的源代碼似乎是左對齊的,但這不是word文檔。 雖然C和C ++使用括號,因此它不會像在Python中那樣工作,但很難理解。
你似乎不明白構造函數是什么。
Obj guy; //Guy as Obj class ... guy.set_pos (0,0);
在C ++中,您可以建立一個構造函數,或至少使用“init”方法進行此類初始化。 嚴格來說,在C ++ 11上,您甚至可以避免這種情況,但重點是您不通過設置方法初始化成員。
女孩被宣布為指向對象Vex的指針:
Vex *女孩
因此,您需要使用 - >運算符而不是。 解決女孩對象成員:
姑娘 - > get_posx();
另外,因為它是指針,你需要用適當的對象初始化它:
Vex * girl = new Vex();
其他方式會出錯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.