0

我做了一些測試... 首先我發佈我的源代碼爲什麼這個數據成員被初始化?

.h文件

class Complex{ 
    private: 
     int r = 0;//initializer 
     int i ; 
    public: 
     Complex(int , int I = 0); 
     Complex(); 
     void print(); 
     void set(int, int I = 1); 
     static void print_count(); 
     static int count; 
}; 

.cpp文件

#include <iostream> 
#include "complex.h" 

int Complex::count = 1; 

Complex::Complex(int R , int I){ 
    r = R; 
    i = I; 

    count++; 

    std::cout << "constructing Complex object...count is " << Complex::count << std::endl; 
} 

Complex::Complex(){//default constructor 
    std::cout << "default constructor is called..." << std::endl; 
} 

void Complex::print(){ 
    std::cout << "r = " << r << ';' << "i = " << i << std::endl; 
    return; 
} 

void Complex::set(int R, int I /*= 2*/){//will be "redefaulting", an error 
    r = R; 
    i = I; 
    return; 
} 

void Complex::print_count(){//static 
    Complex::count = -1;//jsut for signaling... 

    std::cout << "count is " << count << std::endl; 
    return; 
} 

主要功能

#include <iostream> 
#include "complex.h" 

int main(){ 
    Complex d;//using default constructor 
    d.print(); 

    /*Complex c(4, 5);*/ 
    Complex c(4); 
    //c.print(); 

    /*c.set(2, 3)*/ 
    c.print(); 
    c.set(2); 
    c.print(); 

    std::cout << "count is " << c.count << std::endl;//c can access member data 
    c.print_count(); 
    c.count++;// 

    return 0; 
} 

考慮與de構造的Complex對象d故障構造函數

因爲數據部件R與0,執行d.print()時使用初始化, r被預計爲0

且i爲沒有,所以我希望它是垃圾值

但是當我測試時,會發生一件奇怪的事情。

如果我消除的代碼在主文件中的此和下面的行:

的std :: COUT < < 「計數爲」 < < c.count < <的std :: ENDL; // C可以訪問會員數據

然後d.print()會給我的值爲32767在我的系統上,我猜這是一個垃圾值;

但是一旦添加了該行,d.print()只是在我的系統上將i的值賦給0。

我不明白。我沒有設定,修改或初始化我的價值,爲什麼它應該是0?

或者,它也是垃圾值?

或者,調用其中一個函數會破壞i的值?

事情在這裏發生的情況如何?

thx幫助。

回答

2

0就像其他垃圾一樣。否則不要犯錯誤。

形式上,讀取一個未初始化的變量是未定義的行爲,所以沒有必要考慮它:只需通過正確地初始化變量來修復它。

+0

我是C++ 的初學者,花一點時間測試這些並不壞 很高興看到有人在做同樣的事情, –

相關問題