2013-07-24 33 views
0

我有一些C++代碼對象初始化:C++之外產生了錯誤主要

class foo{ 
    public: 
    int a; 
    int b; 
}; 

foo test; 
test.a=1; //error here 
test.b=2; 

int main() 
{ 
    //some code operating on object test 
} 

我得到這個錯誤:

error: expected constructor, destructor, or type conversion before '.' token 

什麼是錯誤的意思是,如何解決?

+2

'test.a = 1;'和'test.b = 2;'是無效的。您不能在功能外進行分配。 – sgarizvi

+1

您不是通過分配給其成員來初始化它。 – chris

+0

縮進使得它看起來好像是Java代碼,主要在類foo中。 – m01

回答

3

它被稱爲構造函數。包括一個將所需值作爲參數的文件。

class foo 
{ 
public: 
    foo(int aa, int bb) 
     : a(aa), b(bb) // Initializer list, set the member variables 
     {} 

private: 
    int a, b; 
}; 

foo test(1, 2); 

正如克里斯指出,你也可以用集合初始化如果字段public,就像在你的榜樣:

foo test = { 1, 2 }; 

這也適用於C + +11兼容的編譯器與我的例子中的構造函數。

+4

也可以使用聚合初始化。 – chris

+0

這是我的第一篇文章..謝謝你們的快速回復 – addousas

1

這應該是:

class foo 
{ 
    public: 
    int a; 
    int b; 
}; 

foo test; 
int main() 
{ 
    test.a=1; 
    test.b=2; 
} 

不能的方法/函數之外編寫代碼,你只能聲明變量/類/類型等

+0

其他的答案也很好,可能有點出色,但我認爲這是最好的,最適合於給定的環境。 – Panzercrisis

0

你需要一個默認的構造函數:

//add this 
foo(): a(0), b(0) { }; 
//maybe a deconstructor, depending on your compiler 
~foo() { }; 
+0

它有一個默認的構造函數和析構函數,並且對象被初始化爲零。 – chris

0

您不能在函數外調用變量初始化。如評論中所述

test.a=1 
test.b=2 

因此無效。如果你真的需要一個初始化,使用像

class foo 
{ 
public: 
    foo(const int a, const int b); 

    int a; 
    int b; 
} 

構造否則你可以把初始化例如進入主要功能。