2015-10-29 88 views
-2

我寫了一個C++程序,當我編譯它,我得到這個警告,無論我打電話Vector3* center = new Vector3(),其實無論我打電話的Vector3()構造函數:C++警告非靜態數據成員初始化

warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11 [enabled by default] Vector3* center = new Vector3();

這裏是我Vector3.h:

class Vector3 { 
private: 
    float x; 
    float y; 
    float z; 

public: 

    // Constructors & Destructor 
    Vector3(float x,float y,float z); 
    Vector3(); 
    ~Vector3(){} 
    // getters & setters & some other functions 
}; 

而且我Vector3.cpp:

#include "vector3.h" 

Vector3::Vector3(){ 
    this->x = 0.0; 
    this->y = 0.0; 
    this->z = 0.0; 
} 

Vector3::Vector3(float x,float y,float z) 
{ 
    this->x = x; 
    this->y = y; 
    this->z = z; 
} 
// others 

我的命令編譯如下:

g++ -O2 main.cpp vector3.cpp 

完全刪除Vector3()構造,並呼籲Vector3* v = new Vector3(0.0, 0.0, 0.0)也沒有工作,我得到了同樣的警告。

我該如何解決這個問題?

編輯:這是一個作業和我不能使用C++ 11.該方案將在部門的計算機,其具有不C++ 11.

+2

[維基百科上的C++ 11](https://en.wikipedia.org/wiki/C%2B%2B11)。此外,您的編譯器消息明確指出如何解決該問題。 – Drop

+3

警告來自一個完全不同的地方(它必須在main.cpp中,因爲你只編譯兩個文件)。 – dasblinkenlight

+0

@kalahari我甚至沒有看到你的代碼中有這樣的一個聲明,像這樣Vector3 * v = new Vector3(): –

回答

0

該錯誤消息暗示這條線進行測試
Vector3* center = new Vector3();
直接在類定義中。該行在函數定義內部是可以的(即使函數定義在類定義內)。

您是否打算將該行直接放入課程中?這意味着center是該類的成員,並且new Vector3()將由該類的每個構造函數(但僅在C++ 11或更高版本中)默認執行。

如果一切是你預期什麼,那裏面class whatever {你需要改變的center的聲明只是Vector3* center;,然後你需要從像whatever::whatever(...) {編輯whatever每一個構造函數whatever::whatever(...) : center(new Vector3()) {

但是,如果你並不打算將center的定義定義爲類的成員(如果您打算在函數中定義局部變量),請檢查和/或發佈該行的上下文,以便獲得更明智的答案。

+0

謝謝,我現在明白了。 – kalahari