2010-04-25 89 views
4

在下面的程序中,是線呼叫基礎類構造

正確/允許?那是否遵循ANSI規則?

#include <iostream> 

class Base 
{ 
public: 
    Base(): x_(0) 
    { 
    std::cout << "Base default constructor called" << std::endl; 
    } 
    Base(int x): x_(x) 
    { 
    std::cout << "Base constructor called with x = " << x << std::endl; 
    } 

    void display() const 
    { 
    std::cout << x_ << std::endl; 
    } 

protected: 
    int x_;  
}; 

class Derived: public Base 
{ 
public: 
    Derived(): Base(1), y_(1.2) 
    { 
    std::cout << "Derived default constructor called" << std::endl; 
    } 
    Derived(double y): Base(), y_(y) 
    { 
    std::cout << "Derived constructor called with y = " << y << std::endl; 
    } 

    void display() const 
    { 
    std::cout << Base::x_ << ", " << y_ << std::endl; 
    } 

private: 
    double y_;  
}; 

int main() 
{ 
Base b1; 
b1.display(); 
Derived d1; 
d1.display(); 
std::cout << std::endl; 
Base b2(-9); 
b2.display(); 
Derived d2(-8.7); 
d2.display(); 

return 0; 
} 
+0

如果OP討論的是ANSI,那麼他使用純C語言可能是 – abatishchev 2010-04-25 10:18:21

+4

@abatishchev代碼看起來像「純C」一樣嗎?還有一個C++的ANSI標準。 – 2010-04-25 10:19:56

+0

@尼爾·巴特沃斯:你說的對,我的疏忽。 – abatishchev 2010-04-25 20:52:22

回答

5

這是允許的,但它毫無意義,因爲編譯器會爲您打電話。不過,恐怕我今天早上不想做標準拖網。

0

這是正確的,但調用基類的默認構造函數是沒有必要的。 假設您使用的是g ++,您可能需要使用以下標誌:-ansi(< => -std = C++ 98)