簡體   English   中英

對於帶有參數化構造函數的 class,創建一個 object 而不傳遞 arguments

[英]For a class with parameterized constructor, create an object without passing arguments

我知道我們不能像標題所說的那樣做。 But why does the below code work just fine & print Value of G in class RT: 2 even though object of class RT is created without passing arguments in the line RT initial_rt;

#include <iostream>
class RT {
    public:
        RT(int var1): G(var1) {std::cout << "Value of G in class RT: "<< G << std::endl;}
    private:
        int G; 
};

class class2 {
    public:
        RT initial_rt;
        class2(RT G) : initial_rt(G) {}
};

int main()
{
    int G=2;
    class2 *cls2_obj = new class2(G);
    return 0;
}

我錯過了什么?

謝謝!

這一行:

RT initial_rt;

只是一個聲明

這一行:

class2(RT G) : initial_rt(G) {}

是 ctor 及其實現

冒號后面的部分稱為初始化列表,這是初始化initial_rt成員的地方。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM