C++ C++;:错误:限定名称的使用无效
更新:我想已经修复了。谢谢大家强> 我犯了个错误,我就是想不出来。 我有以下代码:C++ C++;:错误:限定名称的使用无效,c++,compiler-errors,C++,Compiler Errors,更新:我想已经修复了。谢谢大家 我犯了个错误,我就是想不出来。 我有以下代码: //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 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'
我在谷歌上搜索了这个错误并浏览了几个论坛帖子,但每个人的问题似乎都不一样。我也尝试过在谷歌上搜索“类内的静态结构对象”和其他相关短语,但没有找到任何我认为与我的问题相关的短语
我想做的是:
有一个我从未实例化过的类。在这个类中有一个静态对象,它有一个可以通过构造函数设置的变量
感谢您的帮助。谢谢。您需要使用以下代码:
//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;
}
更新:将静态成员的初始化移动到全局范围
// In global scope, initialize the static member
Structure unInstantiatedClass::structObject(5);
int main(){
return 0;
}
静态成员的定义不能在函数中:
class unInstantiatedClass{
public:
static Structure structObject;
};
Structure unInstantiatedClass::structObject(5);
int main() {
// Do whatever the program should do
}
我认为问题在于 结构unInstantiatedClass::structObject(5);
这是主要的。把它放在一边。不,它已经是一个实例,并且它已经初始化,因为它是
静态的
我手边没有编译器,但肯定会出现同样的错误吗?问题是,定义不能在函数内部,将初始化样式从直接更改为复制不会有什么不同。我同意。我认为静态成员初始化应该移到全局范围。啊哈!我认为这是可行的!谢谢你,也谢谢所有给出答案的人。