我有一些产生错误的C++代码:
class foo{
public:
int a;
int b;
};
foo test;
test.a=1; //error here
test.b=2;
int main()
{
//some code operating on object test
}我得到了这个错误:
error: expected constructor, destructor, or type conversion before '.' token这个错误意味着什么?我该如何修复它?
发布于 2013-07-25 02:41:00
它被称为构造函数。包括一个以所需值作为参数的函数。
喜欢
class foo
{
public:
foo(int aa, int bb)
: a(aa), b(bb) // Initializer list, set the member variables
{}
private:
int a, b;
};
foo test(1, 2);正如chris所指出的,如果字段为public,您也可以使用聚合初始化,如您的示例所示:
foo test = { 1, 2 };这也适用于使用构造函数的C++11兼容编译器,如我的示例所示。
发布于 2013-07-25 02:42:58
这应该是:
class foo
{
public:
int a;
int b;
};
foo test;
int main()
{
test.a=1;
test.b=2;
}不能在方法/函数之外编写代码,只能声明变量/类/类型等。
发布于 2013-07-25 02:44:18
你需要一个默认的构造函数:
//add this
foo(): a(0), b(0) { };
//maybe a deconstructor, depending on your compiler
~foo() { };https://stackoverflow.com/questions/17842215
复制相似问题