main 之外的 C++ 对象初始化

标签 c++

我有一些产生错误的 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 兼容编译器中也适用于构造函数,如我的示例所示。

关于main 之外的 C++ 对象初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17842215/

相关文章:

c# - COM/DCOM : Server stub does not allocate memory for new methods in existing interface

c++ - const_forward 在 C++ 的可选实现中做了什么?

c++ - OpenGL 与 OpenCV 相结合的计算机视觉教程

c++ - 生成带有 GLFW 的窗口,背景颜色不变

c++ - 自定义命令行参数

C++函数调用问题

c++ - GPU 中的 OpenGL 着色有时会抛出 malloc 错误

c++ - FFMPEG:解码视频时,是否可以将结果生成到用户提供的缓冲区?

c++ - 是否可以在 C++ 中返回类似的东西?

c++ - 重命名为 C++ 的 C 文件在重命名后是否可以用 C++ 编译器进行编译?