C++对象在main外部初始化



我有一些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

这个错误意味着什么?我该如何修复它?

它被称为构造函数。包括一个将所需值作为参数的值。

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兼容编译器,如我的示例所示。

这应该是:

class foo
{
  public:
    int a; 
    int b;
};
foo test;
int main()
{
  test.a=1;
  test.b=2;
}

您不能在方法/函数之外编写代码,只能声明变量/类/类型等。

您需要一个默认的构造函数:

//add this
foo(): a(0), b(0) { };
//maybe a deconstructor, depending on your compiler
~foo() { };

不能在函数外部调用变量初始化。如评论中所述

test.a=1
test.b=2

因此无效。如果您确实需要初始化,请使用类似的构造函数

class foo
{
public:
    foo(const int a, const int b);
    int a;
    int b;
}

否则,您可以将初始化(例如)放入主函数中。

最新更新