简体   繁体   English

如何使用已知参数初始化 object,该参数是 C++ 中 class 的成员?

[英]How to initialize an object with known parameters that is a member of a class in C++?

I have the following class:我有以下 class:

class Counter {
private:
    unsigned int count;
    unsigned int inc_by;

public:
    Counter(unsigned int count, unsigned int inc_by) : count(count), inc_by(inc_by) {}

    void increment() {
        count += inc_by;
    }
};

I think have another class Timer where I want to use the Counter object in. However, I want every instance of Timer to have a Counter object private member that is initialized with known parameters.我认为还有另一个 class Timer ,我想在其中使用Counter object。但是,我希望Timer的每个实例都有一个使用已知参数初始化的Counter object 私有成员。 I also can not use dynamic memory allocation.我也不能使用动态 memory 分配。

I have tried the following:我尝试了以下方法:

class Timer {
private:
    Counter counter(0, 1);

public:
    Timer() {}
};

This results in the compiler error Function 'counter' is not implemented .这会导致编译器错误Function 'counter' is not implemented

What am I doing wrong?我究竟做错了什么?

Write

Counter counter { 0, 1 };

You may use only the so-called brace-or-equal-initializers.您只能使用所谓的大括号或相等初始化器。

Or you could initialize the data member in the constructor like或者您可以在构造函数中初始化数据成员,例如

Timer() : counter( 0, 1 ){}

There are only two ways you can initialize non-static data members.只有两种方法可以初始化非静态数据成员。

If you want to give an initial value to a member where it's declared, you need {} , like this:如果您想为声明它的成员赋予初始值,则需要{} ,如下所示:

Counter counter {0, 1};

Otherwise, you can define the initial value in the member initializer list of Timer 's constructor, like this:否则,您可以在Timer的构造函数的成员初始化器列表中定义初始值,如下所示:

Timer() : counter(0,1) {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM