无法将值赋给类中的变量 [英] Can't assign a value to a variable inside a class
本文介绍了无法将值赋给类中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include <iostream>
using namespace std;
class Foo {
int i;
int * p = new int;
*p = 5; // This doesn't worl
// If I instead use int * p = new int(5); it works.
};
为什么呢?我看到,这仅在类内部发生,如果我在主函数上编写了相同的代码,那么它应该可以工作.
Why that? I see that this only occurs inside a class, if I write the same code on the main function it should work.
推荐答案
此语法无效.您不能简单地在类定义中编写代码.相反,您可以编写一个函数,您的代码将在其中运行:
This syntax in invalid. You cannot simply write code inside a class definition. Instead, you can write a function and your code will work inside it:
class Foo {
public:
void bar() {
int * p = new int;
*p = 5;
}
};
int main(int argc, char ** argv) {
Foo f;
f.bar();
}
注意:您应该尽可能在单个语句中分配和初始化变量:
Note: You should prefer to allocate and initialize your variable in a single statement when possible:
int *p = new int(5);
代替:
int * p = new int;
*p = 5;
这篇关于无法将值赋给类中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文