c++: error:无效使用限定名称

C++: error: invalid use of qualified-name

本文关键字:定名称 无效 error c++      更新时间:2023-10-16

更新:我认为它是固定的。谢谢你们了!

我得到一个错误,我只是不知道它。我有这样的代码:

//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;
}

在"Structure unInstantiatedClass::structObject(5);"这一行,我得到了如下错误:

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

我在谷歌上搜索了这个错误,并浏览了几个论坛帖子,但每个人的问题似乎都不一样。我也试着用谷歌搜索"类内的静态结构对象"和其他相关短语,但没有发现任何我认为真正与我的问题相关的短语。

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

任何帮助都是感激的。谢谢。

静态成员的定义不能在函数内部:

class unInstantiatedClass{
  public:   
    static Structure structObject;
};
Structure unInstantiatedClass::structObject(5);
int main() {
    // Do whatever the program should do
}

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

您需要使用以下代码:

UPDATE:将静态成员的初始化移到全局作用域。

// In global scope, initialize the static member
Structure unInstantiatedClass::structObject(5);
int main(){
    return 0;
}