2013-03-02 17 views
2

更新:我认为它是固定的。多谢你们!C++:错误:无效使用限定名称

我得到一个错误,我只是无法弄清楚。 我有这样的代码:

//A Structure with one variable and a constructor 
struct Structure{ 
    public: 
    int dataMember; 

    Structure(int param); 
}; 

//Implemented constructor 
Structure::Structure(int param){ 
    dataMember = param; 
} 

//A class (which I don't plan to instantiate), 
//that has a static object made from Structure inside of it 
class unInstantiatedClass{ 
    public: 
    static Structure structObject; 
}; 

//main(), where I try to put the implementation of the Structure from my class, 
//by calling its constructor 
int main(){ 
    //error on the line below 
    Structure unInstantiatedClass::structObject(5); 

    return 0; 
} 

就行了,说: “结构unInstantiatedClass :: structObject(5);”,我得到一条错误:

error: invalid use of qualified-name 'unInstantiatedClass::structObject' 

我GOOGLE了这个错误并浏览了几个论坛帖子,但每个人的问题似乎有所不同。我也尝试用Google搜索“静态结构对象里面的类”和其他相关的短语,但没有发现任何我认为真的与我的问题有关。

我想要做的是: 有一个我从未实例化过的类。并且在这个类中有一个静态对象,它有一个可以通过构造函数设置的变量。

任何帮助表示赞赏。谢谢。

回答

0

您想使用此代码:

UPDATE:移动静态成员对全球范围内的初始化。

// In global scope, initialize the static member 
Structure unInstantiatedClass::structObject(5); 

int main(){ 
    return 0; 
} 
+0

不,它已经是一个实例,它已初始化,看到它是'静态的' – 2013-03-02 00:29:20

+0

我没有编译器方便,但肯定会给出相同的错误?问题在于定义不能在函数内部,并且将初始化样式从直接更改为复制不会对此产生影响。 – 2013-03-02 00:31:02

+0

我同意。我相信静态成员初始化应该被移到全局范围。 – Tuxdude 2013-03-02 00:33:03

7

静态成员的定义不能是一个函数内部:

class unInstantiatedClass{ 
    public: 
    static Structure structObject; 
}; 

Structure unInstantiatedClass::structObject(5); 

int main() { 
    // Do whatever the program should do 
} 
+0

啊哈!我认为这有效!感谢你,并感谢所有给予答案的人。 – 2013-03-02 00:34:05

2

我认为问题在于 结构unInstantiatedClass :: structObject(5);主要在 。把它放在外面。

+0

是的,没错。谢谢! – 2013-03-02 00:46:41